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>

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

<ng-template #noCourses>
  No courses yet
</div>

2. Hidden attribute 

Using the “hidden” attribute of HTML itself.

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

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

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 [class.active] = "active"><a herf="">Map View</a></li>
  <li><a herf="">ListView</a></li>
</ul>

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

</div>
export class AppComponent{
  viewMode = "map";
}

4. ngFor 

Leave a Reply

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