Tuesday, November 27, 2018

Custom Structural Directive example

Structural directive in Angular manipulate the DOM by adding/removing a set of elements. Attribute directives on the other hand decorate the element with more content/features. Structural directives can be identified with the * mark in front of them. In this example we will create a simple structural directive *ngShow which will show/hide the embedded content based on a condition. Let us start by creating a new directive using the following ng command.
ng generate directive ngShow

This command will create a new directive file, now let us add the directive code to the file as follows.

ng-show.directive.ts
import { Directive, Input, TemplateRef, ViewContainerRef  } from '@angular/core';
@Directive({
  selector: '[ngShow]'
})
export class NgShowDirective {
  constructor(
      private templateRef: TemplateRef,
      private viewContainer: ViewContainerRef) { } 
      @Input() set ngShow(condition: boolean) {
        console.log('condition: ' + condition);
        if (condition) {
          this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
          this.viewContainer.clear();
        }
      }
}

Next we shall use this directive in our component, as follows

app.component.html
<div>
    <h1>
      <div *ngShow="condition">Hello Structural Directive</div>
      <input type="button" (click)='myHandler()' value="Show/Hide Text">
    </h1> 
</div>

In the component class, we use the click handler to toggle the value of condition, this way whenever we click on the button the value of condition we pass to the directive get toggled between true/false. When we pass true to the directive it shows the lable, when we pass false we hide the content.

The click event hander in the component class will be as follows.

app.component.ts
import { Component, OnInit  } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {
  condition: boolean;
  constructor() { }
  ngOnInit() {
    this.condition = false;
  }
  myHandler() {   
    this.condition = !this.condition;   
  }
}

Finally the output will be as follows.





Search Flipkart Products:
Flipkart.com

No comments: