Angular 4 Directives with Examples

Using Directives in Angular 4

Angular 4 Directives - ngFor ngIf ngClass ngStyle

In this tutorial we will be using different structural directives in Angular 4 ngFor, ngIf also we will be using attributes and property bind it like ngClass and ngStyle attributes.

In Angular 4 whenever you use structural directive you should always add '*' before it.

Structural and attribute directives which will be discussed in this tutorial:
  • ngFor
  • ngIf
  • ngClass
  • ngStyle

Angular 4 ngFor

This directive isĀ used to loop within an array or a set of items, for the below example we have a list of students which are declared inside the app class.

App Class Ex.:

 

export class AppComponent {

students= ['Dana','Dina','Dee','Sri'];

}

By using the *ngFor we will list all the students

HTML Example (Unordered list with list items)

<ul>
<li *ngFor="let student of students">Name of Student = {{student}}</li>
</ul>

Expected output:

Name of Student = Mik
Name of Student = Dana
Name of Student = Dina
Name of Student = Dee
Name of Student = Shika

 

Angular 4 ngIf

With ngIf directive you can set a condition and show,hide certain HTML.

In the below example the keyword 'Loged in' will appear only if credential Boolean is true

<h1 *ngIf="credential">Loged in</h1>

Also you can set ngIf condition if a string or variable equals specific value like below example:

<h1 *ngIf="user=='Mike'">Loged in</h1>

In the above example 'Loged in' keyword will appear only if the user value is 'Mike'

 

Angular 4 ngClass

This directive isĀ useful to assign certain classes based on conditions. And since ngClass is a property so instead of using * as ngIf and ngFor brackets will be used instead [ngClass].

In below example a class called wrongPass will be applied on the paragraph if the value of string logged = '0'.

<p [ngClass]="{wrongPass: logged === 0}">Enter your password</p>

Above example requires that you create a class called wrongPass and have a string called logged.

Ex.:

Inside class file:

wrongPass

{

color: red ;

}

 

Angular 4 ngStyle

ngStyle directive is an attribute, to bind it as a property we use brackets [ngStyle], in below example the work Online will be green only if the appPass value is password otherwise it will be red.

 

<h1 [ngStyle]="{color: appPass === 'password' ? 'green' : 'red'}">Online</h1>

 

 


Subscribe to
for video tutorials updates