Structural directives: ngFor - lordoftheflies/angular-essential-training GitHub Wiki
Another common Angular built-in structural directive is ngFor. The ngFor directive is used to repeat markup when looping over some data. Let's put the ngFor to use in the app. We have another new component already added to the project for this lesson named media item list component and the app module and app component are already updated to use that. Let's take a look at the media-item-list.component.ts file. This component is designed to render out a list of media items and uses the media item component to render each one. The class has a property named media items that has some static sample data set to it, for now a couple of media items. Let's flip over to the HTML file for this component and make use of the ngFor structural directive. In the template markup there is a section element with one mw-media-item element inside of that. We want to have a mw-media-item element for each media item in the media items, class property. This can be done by putting asterix ngFor on the mw-media-item element. and setting that equal to a micro syntax statement. This micro syntax is different from a template expression statement. The micro syntax is a specific language syntax that Angular interprets in its own special way. So it expects it to be in a specific format and only supports specific things. The main micro syntax statement for ngFor is "let item of items." So in this case, we want to put "let media item of media items." The let is used to tell Angular to declare a template input variable. The ngFor needs a name for the items of the list It is iterating through to make it available to use within the template. Thus, the let media item. You are free to name that variable, whatever you want. Remember that the asterix is syntactic sugar. So Angular is actually going to put a template element around the MW dash media dash item element making the MW dash media dash item element the one that gets repeated. So with each iteration a new MW dash media dash item element and its contents will get written to the DOM by the ngFor structural directive. We can now use the media item template input variable by putting the media item property binding on the MW dash media dash item element and setting the statement to the media item, template, input variable. And now if we look at the browser we see the list of media items. And if we inspect the list, we can see that the media dash item elements are written out to the DOM. Out of the box, these structural directives not only handle modifying the DOM when they first load up but they also adjust the Dom as the data that is bound changes. So if you have an event like an ad media item that adds one to the media items, property Angular will see that change and rerun the structural directive thus updating the DOM accordingly.