This article will go through the six most common Angular directives: ngFor, ngIf, ngClass, ngStyle, ngModel, and ngSwitch.

What Are Angular Directives?

Angular directives allow you to use if statements and for loops, and add other behavior to the HTML code of an Angular project.

Structural directives involve the structure of the HTML elements. These include ngIf, ngFor, and ngSwitch. Attribute directives involve changing the properties of the HTML elements. These include ngStyle, ngClass, and ngModel.

How to Use ngIf

To use ngIf, you will need a condition to evaluate to true for a particular HTML element to show.

Add two variables to your TypeScript file. In this example, there is a noPlaylists variable and a variable to store the playlists. This variable will evaluate to true if the length of the playlists array is 0. noPlaylists: boolean = false;playlists: any = []; constructor() { }  ngOnInit(): void {    if(this. playlists. length === 0) {      this. noPlaylists = true;    }} In the HTML, add the *ngIf statement. If noPlaylists is true, the error message contained in the span below will appear. Otherwise, it will not. You can apply ngIf to different types of HTML tags.

      There are no playlists available.
To add an "else" component to the if-statement, you will need to add the HTML code for the "else" part in a template block.
      There are no playlists available.
    
        Playlists found.     

How to Use ngFor

If you need to repeat a certain number of blocks on a page, you can use the ngFor directive.

In the TypeScript file, add items to the array. playlists: any = [   {“name”: “Rock”, “numberOfSongs”: 5},   {“name”: “Contemporary”, “numberOfSongs”: 9},   {“name”: “Popular”, “numberOfSongs”: 14},   {“name”: “Acoustic”, “numberOfSongs”: 3},   {“name”: “Wedding Songs”, “numberOfSongs”: 25},   {“name”: “Metal”, “numberOfSongs”: 0},]; In the HTML file, add the *ngFor statement. Playlists found. <div *ngFor=“let playlist of playlists” class=“item”>    

       {{playlist. name}}       {{playlist. numberOfSongs}} songs