Directives in Angular Applications

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] earlier in the course you learned about ng 4 which is one of the built-in directives and angular that we use for rendering lists in this section we're going to look at in g4 in more detail we're also going to look at the other built-in directives including ng F and just switch case into class and ng style and finally we'll wrap up this section by looking at building custom directives in angular so let's get started there are times that you may want to show or hide part of a page depending on some condition so here in app component I'm gonna define a field courses set it to an array with two items now for now we're just gonna use simple numbers in a real world application you're gonna have the actual course objects but let's not worry about that and just focus on showing or hiding part of a page now in our app that component that HTML file if you have any courses in this array we want to render them in a list otherwise we want to display a message to the user like there are no courses yet so first I'm going to create a div this is where we're gonna display the list of courses now here again I'm simplifying this example if you want to render the list of courses you would use a ul and Li with the ng4 directive so here's one day for displaying the list of courses and here's another for displaying a message like no courses yet you want to render one day for the other depending on the number of items in our courses array for that we use the ng-if directive so to refresh your memory we use directives to modify the Dom now there are two types of directives structural directives modify the structure of the Dom by adding or removing Dom elements attribute directives modify the attributes of Dom elements so here we want to change or modify this structure of our Dom we want to add or remove one Dom element so whenever you're using structural directives you need to prefix them with an asterisk and I'm gonna explain the reason later in this section so asterisk ng if now here we add the condition if this condition evaluates to true the-- this div will be rendered in the Dom so we can add something like courses that length greater than zero now you don't necessarily have to write the condition here you may have a method in your class like this do we have any courses and we call this method we get some value if that value evaluates to true see then this dip will be rendered now let's revert this back now we can use the same technique or the other div and this is the old approach before angular 4 so let's see how that works ng if I want to render this Dave if we don't have any courses so courses that length equals zero now back in the browser so because we have two items in our array we see the list of courses message now back in our component I'm gonna empty this array save like in the browser now we get no courses yet message let's inspect this so here under app route look we have only one div which is the div with the message no courses yet so the other div is not in the Dom and that's what I want you to pay attention to so when you use ng if if this condition evaluates to true see this element will be added to the Dom otherwise it will be removed from the Dom now in angular for now we have a slightly different syntax to implement the exact same feature so instead of repeating in G if twice with this condition reversed we can implement it using an if and else kind of approach just like how we have F and LS in a lot of programming languages so first we need to change the type of this second element from div to ng template so ng - template then we remove this ng if make the code cleaner but we need to assign this template and identifier earlier you learned that you can use this hashtag to define a template variable let's call this block no courses then we modify our ng if so after the condition we add a semicolon and we type else and then the name of our template variable no courses note that I didn't add this hashtag here just the name of our template variable so if this condition is true see this block will be rendered otherwise the other block let's try it back in the browser so currently we don't have any courses and that's why we see this message if I go back in app component and add a couple of items here now we see the list of courses now you may not quite like this syntax because in the first block we're using a div in the second block we're using ng template they're kind of inconsistent there is another approach so we can define another ng template here ng template and this is for displaying the list of courses so we assign it an identifier like courses list and here we add that message list of courses okay now we have one div with two templates one for the condition that is true C and the other for condition that is policy okay now we need to change our njf so first we add our condition if this condition is true C right then and here we specify the name of our ng template so courses list and then we have LS and here's the other block so note that we have a semicolon after the condition then we have then as a keyword here is the name of our target block or target template after that we have else as a keyword and finally the name of the other template I personally prefer this approach because it's more clear and more consistent now there is another approach to show or hide part of a page and that's what I'm going to show you in the next lecture now back in the same example let me show you another way to show or hide part of a page instead of using the ng-if directive we can use the hidden attribute so in HTML you know we can apply this hidden attribute to our divs to hide them if you go back in the browser we should see no courses yet message here's the message beautiful now this attribute in HTML also exists as a property in our Dom objects so we can use property binding and bind this property of the underlying Dom object to some expression for example here I want to hide this first div if we don't have any courses so courses that links equals 0 now similarly we can hide the second div if we have at least one course so courses the length greater than 0 now back in app component currently we have two items here let's see if application is working properly so we get the list of courses beautiful now back in app components I'm gonna empty this array save and back in the browser no courses yet beautiful now let me show you something let's inspect this element note that both divs exist in our Dom but the first tip has the hidden attribute and that's why it's hidden so that's the main difference between using ng F and the hidden property when we use ng F on an element if the condition evaluates to false II that element is removed from the dawn whereas when we use the hidden attribute the element is in the Dom is just hidden so you might ask which approach is better well if you're working with a large tree with a lot of children it's better to use ng F because these elements can take substantial memory and computing resources you don't want to put them in the Dom if you're not gonna show them to the user plus angular may continue to check for changes even to invisible properties so the change detection mechanism in angular that's the mechanism that keeps your views in sync components that's running in the background and when these elements are in the Dom angular continues to perform change tracking on these elements so in these situations if you're dealing with a large tree with a lot of diorama objects it's better to use ngf to free up resources there is just one exception in some situations building a large element tree in the right state may be costly so if you have a page with an element subtree in that case and you if may have a negative impact on the performance of that page so if the user is going to click a button to toggle something to show or hide that part of the page if building that elementary is costly you shouldn't use ng if it's better to keep it in the Dom and hide it using the hidden attribute so in summary if you're dealing with a small tree of objects it doesn't matter which approach you choose it's purely your personal preference if you're working with the large tree first check to see if building that tree is going to be costly or not if it's costly use the hidden property to keep it in the Dom but hide it otherwise it's better to use ng if to remove it from the Dom and free up the resources in angular we have another directive called ng-switch case which is very similar to the concept of switch case we have in a lot of programming languages so imagine we want to build a page to display properties on a map or in a list so here we have two tabs map view and list view when we select the list view we see the list view content and when we select a map view we see Matthew content so let me show you how to implement this with ng-switch case and by the way you can implement the exact same thing with ng-if but ng-if works only if you have a true c and a falsie condition in this case we might have multiple tabs so we cannot implement that using ng-if and that's why we need ng switch case so in app component on HTML i want to add some basic markup to render bootstrap tabs so here we want a UL and this UL should have two classes so we add dot nav and also dot nav - pills this syntax you see here is what we call Zen coding and with this we can quickly generate HTML markup so tab now we have a ul with these two classes now inside this ul we want an Li and inside this Li we want an anchor now we want two of these elements so I put them in parentheses x to tab and this is what we get now let me temporarily make the first li active so I apply the active class here and name this map view the second Li the anchor should be called list view now below that will have a div and here will have either the content of the map views of map view content or list view content now I want to temporarily comment this out because one div one content div will be rendered dynamically now let's just make sure that our markup is working back in the browser all right it looks good beautiful now let's move on and make this dynamic so let's go to our app component here we need to define a field to keep track of the currently selected tab we can call this View mode and we can set this initially to map and then we can change this to a list so it can hold one of these two values map or list now back in our template let's bring this div back we want to render one of these divs dynamically based on the value of View mode field so on this top parent div we're gonna apply property binding so angular adds a new property to our Dom elements that is not part of the standard Dom this property is called ng-switch we can use property binding and just switch and bind this to a field in our class like View mode now an HD will apply ng switch case directive and because with this directive we add or remove a Dom element this is a structural directive and we should prefix it with an asterisk so ng switch case now if the value of view mode is map so map as a string note that I put map in single quotes let me zoom in so we have double quotes which is for the value of this directive and we have single quotes which is for the map as a string okay now similarly for the other div I'm gonna apply ng switch case we want to render this Dave if the value of view mode is list now optionally we can have another div so if the value of view mode is something else I want to render this div so here we add ng-switch default and it doesn't have a value yeah I played like an attribute okay so let's add some label here otherwise right so this is we use the engine switch directive now finally we want to make this class active dynamic so we can use class binding you put it in square brackets class dot active and we want to render this if view mode is set to map so we can write a simple conditional statement here view mode equals map okay and similarly for the other Li I'm gonna add another class binding class that active we set this if view mode equals list now finally when we click these links here you want to change the view mode so let's remove this href attribute we use event binding and bind the click event to an expression now here we can simply call a method in our class like change view mode and simply pass a string like map but that method is going to be a one-liner so we can simply write that expression here so we simply set view mode to map ok and I'm gonna copy this and apply to the other link as well but this time I'm gonna change this value to list all right now let's test the application so back in the browser initially the map view is visible because we set the view mode to map in our component if we click list we go to the list view and back to the map view now back in the component I'm gonna change this value to something else with this this other div that we applied ng-switch default directive to this one should be rendered so look we get the otherwise message here so here's the lesson if you want to compare the value of the field or a property against multiple values use the ng switch case directive all righty I've seen the ng4 directive before we use this directive to render a list of objects so let's review this one more time and this time I'm going to show you more details about this directive so here in app component I'm gonna define a new field called courses and set this to an array of objects in this array we're going to have three course objects and for each course we're going to have two properties one is ID and the other is the name so of course one now I'm going to duplicate this so ID two and three and obviously course two and course three now let's use the ng4 directive to render these on the view so app dot component at HTML we want to have a ul and inside this ul we need an Li tab that's the markup now we add ng for and here as the value with type let course of courses and then we can use interpolation to render the name of each course so course that name let's make sure the application works up to this point so back in the browser okay we got three courses on the screen beautiful now this ng4 directive exports a bunch of values that might help you build certain features for example imagine you want to render a table and you want to highlight the first row or maybe you want to highlight the last row or you want to highlight the odd or even rows or maybe you want to display an index next to each object we can use the exported values from ng for directive so here after this expression we had semicolon one of these exported values is index so we type index now we need to alias this to a local variable so we type as and then the name of our local variable like I so with this expression we get the value of the index and put it in a local variable called I and then we can use interpolation to render I on the screen so like this I all right now let's test this back in the browser look before each course we have its index in our courses field so as you can see the index of the first item or the first course is zero now index is one of these exported values there are several other let me show you how you can find the list of all these exported values so if you head over to angular dot IO in the search box you can search for ng4 of directive s anyway our directive even though in HTML we use ng 4 but the actual name of this directive is ng for off and you can see that here it has a d' icon which indicates our directive now in this page if you scroll down under local variables you can see all these exported values so you saw index we also have first last even and odd so let me show you one more example let's say we want to render a table and you want to highlight all the even rows so you can get access to the even value an alias this as a local variable is even because this even is a boolean unlike the index which is a number even odd first and last values they are all boolean now here next to each course I want to render a span and I want to render this only if this is an even row so ng if is even for now I just add a simple label now in your applications you might want to render a table so you can use this variable is even and apply some style or some class to even rows in your table now let's try this back in the browser so you can see in front of the first and the third rows we have this label even all right now let me show you how this ng4 directive responds to the changes in the component state so on the top I want to add a button with this button we want to add a new course in our list so here we can handle the click event and bind this to a method called on add ok now back in the component let's add this new method here so on add we call this that courses let push and we push in your object here ID for a name it's going to be course for save back in the browser so here we have three courses when I click the Add button we get a new course here so angular has this change detection mechanism so whenever you click a button or when I ran Ajax request or a timer function completes angular performs its change detection it looks at our component it knows that this course is filled now has a new object that's the course with ID 4 so then it will render that course using this template now similarly we can add a button next to each course to remove it so button remove and here we can handle the click event and bind this for this expression we're gonna call on remove method in our class and as an argument we can pass this course object and we have in each iteration that is the course object here ok now back in the component so similarly I'm gonna add another method on remove here we get a course object now to remove this from an array first we need to find the index of this course in array so this of course is that index of this course object we get the index and then we call this that courses that splice so we go to that index and delete one object let's try it so back in the browser now if I click this remove button course number two will be removed there you go so once again after the execution of this on remove method angular performed it's changed detection it realized that one of the objects in our courses array is no longer there so it removed the corresponding list item in the Dom now similarly if we modify an existing object again angular will refresh the Dom automatically so let's change the name of this method from Unruh moved on change back in the component rename it here now instead of removing this course from the array I'm simply gonna change its name update it like that let's test the application you forgot to change the label it doesn't matter so when we click this the name of the course changes again this is change detection in action in the next lecture we're going to look at this change detection from a performance point of view hi thank you for watching my angular tutorial if you enjoyed this video please like it and share it with others also you can subscribe to my channel for free new videos every week this video is part of my complete angular course with almost 30 hours of high quality content where you learn everything about angular from the basic to the advanced topics all in one course so you don't have to jump from one tutorial to another in case you're interested you can get this course with a big discount using the link in the video description and if not that's perfectly fine continue watching as the next section is coming up
Info
Channel: Programming with Mosh
Views: 117,901
Rating: 4.9028797 out of 5
Keywords: angular, angular.js, angularjs, angular 2, angular2, angular 4, angular4, mosh hamedani, javascript, jquery, directive, ngif, ngswitchcase, ngfor, programming with mosh, code with mosh
Id: LtT01ZCHRjk
Channel Id: undefined
Length: 25min 13sec (1513 seconds)
Published: Wed Sep 06 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.