Thursday 27 December 2018

Using structural directives in Angular

Background

There are 3 kinds of directives in 
  1. Components—directives with a template.
  2. Structural directives—change the DOM layout by adding and removing DOM elements.
  3.  Attribute directives—change the appearance or behavior of an element, component, or another directive.
We have already seen how to create components, how components interact with each other. Structural Directives change the structure of the view whereas Attribute directives are used as attributes of elements. You can use build in directives provide by angular or build your own.

In this post, I will explain structural directives such as *ngIf and *ngFor.


Using structural directives in Angular

As mentioned before structural directives manipulate the DOM structure by adding or removing elements from the DOM.  An asterisk (*) precedes the directive attribute name. Let's see an example by using *mgIf. This structural directive is used to decide if the element on which it is applied (including its children) are added in DOM or not.

So in your AppComponent code make changes so that the HTML template looks like below -

<div class="hello-world">

  <h1 *ngIf="showMessage">Hello World!</h1>
  <br/>

  <button (click)="toggleVisibility()">Toggle Visibility</button>
</div>


Notice the way we are using *ngIf. It says if showMessage variable evaluates to true then show this h1 element and if not remove it from the DOM. Then we have a button which says "Toggle Visibility" that essentially toggles the showMessage variable flag. Let's see the component typescript code to understand this better. Your component code would look like following -

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


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  showMessage: boolean = false;

  toggleVisibility = () => {
    this.showMessage = !this.showMessage;
  }

}


Notice the showMessage variable of type boolean. It is set to false at the beginning and as you click the button this flag is toggles which change the visibility of our H1 element. Please note that *ngIf removes the element from the DOM and does not just change the visibility. So when I say changes visibility I mean it being part of the DOM. So let's give this a try. Start your app with -
  • ng serve





Notice how the h1 elements take part of DOM and when it is not visible it gets removed. Your button position will get adjusted based on that.

NOTE: When the condition is false, NgIf removes its host element from the DOM, detaches it from DOM events (the attachments that it made), detaches the component from Angular change detection, and destroys it. The component and DOM nodes can be garbage-collected and free up memory.

The asterisk is "syntactic sugar" for something a bit more complicated. Internally, Angular translates the *ngIf attribute into a <ng-template> element, wrapped around the host element.


Now let's take a look at *ngFor directive.

Change the component code to have an array of cities.


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  cities: string[] = ["Mumbai", "Bangalore","Delhi","Chennai","Hyderabad"];

}


Now you can change this components HTML code as follows -

<div class="hello-world">
  <ul>
      <li *ngFor="let city of cities">{{city}}</li>
  </ul>
</div>


This essentially creates an unordered list element and inside it, iterates over each of the cities in the array and creates a list element. This would look like below -




NOTE: Angular desugars this notation into a marked-up <ng-template> that surrounds the host element and its descendants. Each structural directive does something different with that template.

As mentioned before you could also create your own structural directives. To read more on these go to the angular documentation - https://angular.io/guide/structural-directives

Related Links

No comments:

Post a Comment

t> UA-39527780-1 back to top