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
Inside the ngFor, you will be able to reference each object in the array using the “playlist” variable.
“playlist.
name” and “playlist.
numberOfSongs” will print both attributes within the tag.How to Use ngClass#
You can change the styling class that a particular div uses, based on a condition.
Add two classes into the CSS file with different styles.
You can add any kind of CSS styling you want, such as different background colors.
.
songs { background-color: #F7F5F2;}.
noSongs { background-color: #FFA8A8;} Within the for-loop from the previous step, add the ngClass attribute directive.
[ngClass]=“playlist.
numberOfSongs > 0 ? ‘songs’ : ’noSongs’” is using the same ternary operator that JavaScript and other languages use.
0 ? 'songs' : 'noSongs'">
{{playlist.
name}} {{playlist.
numberOfSongs}} songs
If the number of songs is greater than zero, it will apply the "songs" class to the div.
This will give the div a gray background color.
Otherwise, if the number of songs is zero, it will apply the "noSongs" class to the div.
This will give the div a red background color.How to Use ngStyle#
Instead of using ngClass, you can use ngStyle if you want to apply in-line styling instead of styling via a class.
Change the ngClass from the previous step to use ngStyle instead.
0 ? '#F7F5F2' : '#FFA8A8' }>
{{playlist.
name}} {{playlist.
numberOfSongs}} songs
If you need to apply more than one inline style, you can separate each style with a comma.
[ngStyle]="{'background-color': playlist.
numberOfSongs > 0 ? '#F7F5F2' : '#FFA8A8', 'color': playlist.
numberOfSongs > 0 ? 'black' : 'darkblue' }"How to Use ngModel#
You can use ngModel for two-way binding. This means you can pass the value of an attribute between both HTML and TypeScript files.
For instance, say you have an input element in the HTML file that uses ngModel. The ngModel attribute is bound to a variable in the TypeScript file. When you enter a value into the input, it will update the variable in the TypeScript file.
The changes made to the attribute in the TypeScript file will also reflect in the HTML if other divs are using that variable.
In app.
module.
ts, add the FormsModule into the imports at the top of the file, and also to the imports array.
import { FormsModule } from ‘@angular/forms’;@NgModule({ imports: [ .
.
.
FormsModule ]}) Add an attribute in the TypeScript file to keep track of when the user is renaming a playlist.
renamingPlaylists: boolean = false; Make the playlists variable public so that this can be accessible when using ngModel in the HTML file.
public playlists: any = [ .
.
.
]; Add two buttons in the HTML file, which will allow you to rename or cancel renaming each playlist.
<button type=“button” class=“btn btn-info” *ngIf="!renamingPlaylists" (click)=“renamingPlaylists=true”>Rename Playlists<button type=“button” class=“btn btn-info” *ngIf=“renamingPlaylists” (click)=“renamingPlaylists=false”>Stop renaming Add an input box inside each playlist’s div.
The input will only be visible when you click on the Rename Playlist button.
This input box will have an ngModel bound to “playlist.
name”.
<input type=“text” *ngIf=“renamingPlaylists” class=“form-control input-field” id=“name” required [(ngModel)]=“playlist.
name” /> When you enter a new name into the input box, playlist.
name will update in the TypeScript file.
This will also then update the other divs in the HTML file that use playlist.
name.
How to Use ngSwitch#
You can use ngSwitch to display certain elements based on the cases within a switch case.
Add a new “rating” attribute to the objects inside the playlists array.
This attribute can be any number between 0 and 5 (inclusive).
public playlists: any = [ {“name”: “Rock”, “numberOfSongs”: 5, “rating”: 5}, {“name”: “Contemporary”, “numberOfSongs”: 9, “rating”: 1}, {“name”: “Popular”, “numberOfSongs”: 14, “rating”: 5}, {“name”: “Acoustic”, “numberOfSongs”: 3, “rating”: 4}, {“name”: “Wedding Songs”, “numberOfSongs”: 25, “rating”: 5}, {“name”: “Metal”, “numberOfSongs”: 0, “rating”: 0}, ]; Add a switch case below the name and number of songs for a playlist.
Based on the rating number for the playlist, the playlist will show the correct number of stars.
{{playlist.
name}} {{playlist.
numberOfSongs}} songs
★
★★
★★★
★★★★
★★★★★
No ratings
Learning More With Angular#
Now you have learned the basics of Angular directives, including how to use ngIf, ngFor, ngClass, ngStyle, ngModel, and ngSwitch. You can combine them to create more complex user interfaces. There is so much more for you to explore and learn about Angular, no matter whether you are a beginner or at an advanced level.