Categories
Angular

ng if else condition in angular with example

In this post, we will learn about ng if else condition in angular with example

NgIf the directive will be used to display DOM based on a condition. It is very useful to show or hide a HTML div

Sample Code
<div ngIf="show">
    <p>This is can be show</p>
</div>
import { Component, OnInit } from '@angular/core';
import { StudentService } from '../../service/student.service';
import { Student } from '../../model/student.model';

@Component({

  selector: 'app-student-details',
  templateUrl: './student-details.component.html',
  styleUrls: ['./student-details.component.css']
})
export class StudentDetailsComponent implements OnInit {

  constructor() { }

  show: boolean;

  ngOnInit(): void {   
    this.show=true;
  }

}

In the above example, we declared a boolean variable called as show. We are changing that boolean value to true on ngOnInit method

In the html file we are using that show boolean variable to display the paragraph tag

if the show boolean is false then the html div will not display

ngIf else Example

We need to define the else block inside a ng-template block. below is the example for ng if else condition

<div ngIf="show; else notshowing">
    <p>This is can be show</p>
</div>

<ng-template #notshowing>
    <p>This will be shown on else statment</p>
</ng-template>
Conclusion

In the above post, we learned about ngIf else condition in angular with example

Related Articles

http post request from angular with example

Leave a Reply

Your email address will not be published. Required fields are marked *