Skip to main content

Lab 3: Directives (ngIf & ngFor)

Objectives

  • Use angular ngIf and ngFor directives

Instructions

Step 1 - ngIf directive

  • In the app.component.ts component, create a variable called showAlbumOfTheDay and set it to true.
    • Above the albumOfTheDay display, add a button that will toggle the showAlbumOfTheDay variable fromt true to false and othjer way around.
  • It will display "Hide" if the showAlbumOfTheDay is true and "Show" if it is false.
  • Use the ngIf directive to display the albumOfTheDay only if the showAlbumOfTheDay variable is true.

Step 2 - ngFor directive

  • Create a new component called album-list and display the list of albums in the app.component.html file, above the album-of-the-day component.
  • In the album-list component, create a variable called albums and assign an array of objects that respect the Album interface.
  • Use the ngFor directive to display the list of albums in the album-list component.

At this level app.component.html should look something like:

    <app-albums-list />
<a class="link" (click)="showAlbumOfTheDay = !showAlbumOfTheDay">{{showAlbumOfTheDay ? 'hide' : 'show' }} album of the day</a>
<app-album-of-the-day *ngIf="showAlbumOfTheDay"></app-album-of-the-day>

Instructions - Step 2

It is also possible to iterate over a list of elements that would come from a function. Let's create a function that will return the list of albums based on a search term.

Moving the search form

  • Move the search form from the app.component.html to the album-list component.

[hint] don't forget to move the variable searchTerm to the album-list component.

Using filter to filter existing albums

  • In the album-list component, create a method called albumsFiltered that will return filtered albums based on the searchTerm variable.
  • Use the albumsFiltered method to filter the albums displayed in the album-list component.

[HINT] Here is an example of how it can be done

albumsFiltered(): Album[] {
return this.albums.filter(album => {
return album.title.toLowerCase().includes(this.searchTerm.toLowerCase())
})
}
  <li *ngFor="let album of albumsFiltered()">{{ album.title }}</li>

Resources

Album list