Design a site like this with
Get started

Angular JS NgIf and NgFor and NgSwitch

clouds daylight forest grass

In this Example we will see inbuilt angularjs Directives

  1. NgIf
  2. NgFor
  3. NgSwitch

NgIf ,NgFor and NgSwitch

Lets go through basics first


This directive is used when you want to display or remove an element based on a condition.

The syntax is: 



This directive is getting used to iterate through collection

The syntax is:    

<ul *ngFor =" let n of newcars">


NgSwitch is like the JavaScript switch statement. It displays one element from among several possible elements, based on a switch condition. Angular puts only the selected element into the DOM.

NgSwitch is actually a set of three, cooperating directives: NgSwitchNgSwitchCase, and NgSwitchDefault as in the following example.

The syntax is:    

<ul *ngFor=" let c of newcars" [ngSwitch]="">

            <li *ngSwitchCase="'city'" class="blue-text text-darken-2">{{ }} {{ c.average }}
            <li *ngSwitchCase="'polo'" class="blue-text text-darken-2">{{ }} {{ c.average }}

            <li *ngSwitchDefault class="text-success">{{ }} {{ c.average }}


Create your AngularJs Application

Please follow steps mentioned in below post

Hello World with Angular JS

Prerequisites Angularj JS new version is using nodejs for setting up application and for running applicaion you will also need any code editor tool. For current setup we are using visual code studio Kindly down load latest version of nodejs and visual code studio on your machine and complete setup Node Installation 1 Go to…

Create Components

In this example we have created multiple component which can be refereed in git repo

Use below command to generate these components

ng generate component <componentname>

For demonstrating this we have created below component in git project

ng generate component NgIfNgForNgSwitchComponent

Please refer:

Lets look at code of this one


<p>ng-if-ng-for-ng-switch works!</p>

<div class="row">

    <div class="col s3" style="border: brown; border-style: dashed; margin: 10px;">

        <ul *ngFor=" let c of cars">

            <li> {{c}}</li>

    <div class="col s3" style="border: brown; border-style: dashed; margin: 10px;">
        <h4>Display data with ngFor and ngIf</h4>

        <ul *ngFor=" let n of newcars">

            <li style="color:red" *ngIf="n.average < 7 "> {{}}</li>



    <div class="col s4" style="border: brown; border-style: dashed; margin: 10px;">
        <h4>Display data with Switch Directive</h4>
        <ul *ngFor=" let c of newcars" [ngSwitch]="">

            <li *ngSwitchCase="'city'" class="blue-text text-darken-2">{{ }} {{ c.average }}
            <li *ngSwitchCase="'polo'" class="blue-text text-darken-2">{{ }} {{ c.average }}

            <li *ngSwitchDefault class="text-success">{{ }} {{ c.average }}



In this code we are first printing all car names using for loop

In second for loop we are filtering cars whose average is less than 7.

In third block we are using switch case so we can apply different class to different cars based on name comparison


import { Component, OnInit } from '@angular/core';
import { Car } from '../car';

  selector: 'app-ng-if-ng-for-ng-switch',
  templateUrl: './ng-if-ng-for-ng-switch.component.html',
  styleUrls: ['./ng-if-ng-for-ng-switch.component.css']
export class NgIfNgForNgSwitchComponent implements OnInit {

  constructor() { }

  title = 'Display Cars';
  cars = ['city', 'nexon' , 'vento'];

  newcars = [
new Car('city', 10),
new Car('polo', 5),
new Car('vento', 6),

  ngOnInit() {


In this component we are populating array of cars.


export class Car {
    name: string;
    average: number;

    constructor( name , average) { = name;
        this.average = average;


In Above code we have declared car as class and with if we are filtering out some of cars based on use of different combination of ngIf,ngfor and ngswitch directives

After running this it will show below output


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TwowaybindingwithNGModelComponent } from './twowaybindingwith-ngmodel/twowaybindingwith-ngmodel.component';
import { FormsModule } from '@angular/forms';
import { NgclassandngstyleComponent } from './ngclassandngstyle/ngclassandngstyle.component';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Add Materialize css in index.html

In Index.html we will add materialize css and js file to use elegant UI

<!doctype html>
<html lang="en">
  <meta charset="utf-8">
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="">

  <!-- Compiled and minified JavaScript -->
  <script src=""></script>

We have added js file and css file specific to materilize css

Edit app.component.ts : This is parent component


import { Component } from '@angular/core';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'AngularJSInBuiltDirectives';


Edit app.component.html

We have added ngmodel component in app.component.html

We have added all components mentioned above in tutorial .You can remove or add as per you need.



    <div class="card-panel   yellow lighten-3">
    <div class="card-panel    lighten-3">



In main html we have imbedded all three components.

Run Application

If you clone entire project then first run npm install so all dependencies will get downloaded.

Then run below command

ng serve --open

You will get below kind of output for your project once it get compiled and it will open your application in browser

9. Check Outpput

go to http://localhost:4200 path in browser

This example demonstrated that ngIF and NgFor working fine

We have combined all above mentioned examples on single page in in git repo in app.component.html and it will look like below on browser so you can play with all 3 components

Source Code:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: