Angular

Last Updated: 8/22/2023

ngIf

  • Use ngIf to show or hide part of a page depending on condition
  • Whenever using structural directives prefix them with asterisk *
  • If the condition evaluates to truthy, element will be added otherwise removed from DOM

app.component.ts

courses = []

app.component.html

Option 1

<div *ngIf="courses.length > 0">List of Courses</div>
<div *ngIf="courses.length == 0">No courses</div>

Option 2

<div *ngIf="courses.length > 0; else noCourses">List of Courses</div>
<ng-template #noCourses>No courses</ng-template>

Option 3

<div *ngIf="courses.length > 0; then coursesList else noCourses"></div>
<ng-template #coursesList>
	List o f Courses
</ng-template>
<ng-template #noCourses>
	No courses
</div>