Angular – Directives

There are to types of Directives :

  • Structural: Modify the structure of the DOM
  • Attribute: Modify the attributes of DOM elements

1. ngIf

export class AppComponent {
  courses = [1,2]; 
  courses = [];
//Instinctual version 
<div *ngIf="courses.length > 0">
  List of courses

<div *ngIf="courses.length == 0">
  No courses yet
// Better version 
<div *ngIf="courses.length > 0; then coursesList else noCourses">
  List of courses
<ng-template #courseList>
  The list of courses

<ng-template #noCourses>
  No courses yet

2. Hidden attribute 

Using the “hidden” attribute of HTML itself.

<div [hidden] = "courses.length == 0">
  List of courses

<div [hidden] = "courses.length > 0">
  No courses yet

using *ngIf, the hidden part will not be loaded into HTML at all.

using the hidden attribute, the hidden part still going to be loaded into HTML anyway.

if you are dealing with a large element tree, use *ngIf, it saves computational recourses. 


3. ngSwitchCase

<ul class = "nav nav.pills">
  <li [] = "active"><a herf="">Map View</a></li>
  <li><a herf="">ListView</a></li>

  <div *ngSwitchCase="'map'">Map View Content</div>
  <div *ngSwitchCase="'map'">List View Content</div>
  <div *ngSwitchdefault>other</div>

export class AppComponent{
  viewMode = "map";

4. ngFor 

Leave a Reply

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