Angular Directives List tutorial with examples
In this tutorial, we are going to learn about different types of built-in directives in angular.
Contents
ngIf
ngIf directive helps us to add or remove HTML elements conditionally into the dom.
Example:
<h1 *ngIf="isActive">Im happy</h1>
In the above code, we have added *ngIf="isActive"
so that h1
element will only render into the dom if isActive
property is true
.
ngFor
ngFor directive helps us to loop over the array of items and render each item into the dom.
Example:
<ul>
<li ngFor="let user of users">{{user}}</li></ul>
Here we added a ngFor="let user of users"
where users
is an array we are looping, on each iteration user
variable, is pointing to the different user present in the array.
ngModel
ngModel helps us to do two-way data binding in angular it means we can sync the data in both directions.
To use ngModel
directive first we need to import the FormsModule
inside our app.module.ts
file and add it to the imports array.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule ],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Using ngModel
directive
<input [(ngModel)]="hello" />
In the above code, we have added [(ngModel)] = "hello"
to input element where hello
property binds
to the input value in both directions.
ngClass
ngClass directive helps us to add or remove CSS class names dynamically based on a particular condition.
Example:
<h1 [ngClass]="[isActive ? 'red' : 'green']">Hello angular</h1>
In the above code, we have added [isActive ? 'red' : 'green']
to ngClass
directive where isActive
is an expression and red
,green
are css class names.
If isActive
is true red
class is added to h1
element otherwise green
class is added.
ngStyle
ngStyle directive helps us to set inline styles to HTML elements.
Example:
<h1 [ngStyle]="{'background-color': mycolor}">Hello angular</h1>
Here we have added an object {'background-color': mycolor}
to ngStyle
directive where background-color
is a CSS style name and mycolor
is a JavaScript expression to be evaluated.