11.Directive
Directive
Directives – Directives are nothing but custom html element that angular provide.
To add or remove html elements from or to DOM, directives are used.
Directives are js class and declared as @directive. There are 3 directives in Angular.
- Component Directives
- Structural Directives
- Attribute Directives
Component Directives: Component directives are used in main class. They contain the detail of how the component should be processed, instantiated and used at runtime.
Structural Directives: Structural directives start with a ‘*’ sign. These directives are used to manipulate and change the structure of the DOM elements.
For example,
*ngIf – to conditionally render html elements.
*ngSwtich - to conditionally render html elements.
*ngFor- to render list of html elements.
Attribute Directives: Attribute directives are used to change the look and behavior of the DOM elements. For example: ngClass, ngStyle etc.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-directives',
template: `
<p style="color:red;text-align:center">THIS IS {{componentName}} DIRECTIVE<p><hr>
<p>-------- directives IF --------</p>
<p *ngIf = "true">*ngIf = "true"</p>
<p *ngIf = "false">*ngIf = "false"</p>
<p *ngIf = "isVisible">*ngIf = "isVisible :- "{{isVisible}}</p>
<p *ngIf = "isVisible else tTwo">*ngIf = "isVisible; else tTwo :- " {{isVisible}}</p>
<p *ngIf = "!isVisible then tOne else tTwo"></p>
<ng-template #tOne><p>ng-template #tOne</p></ng-template>
<ng-template #tTwo><p>ng-template #tTwo</p></ng-template>
<p>-------- directives SWITCH --------</p>
<div [ngSwitch]="color">
<p *ngSwitchCase = "'red'">*ngSwitchCase = "red"</p>
<p *ngSwitchCase = "'green'">*ngSwitchCase = "green"</p>
<p *ngSwitchDefault>*ngSwitchDefault</p>
</div>
<p>--------directives LOOP --------</p>
<div *ngFor="let name of names;index as i;first as f;last as l;odd as o;even as e">
<p>Hello {{name}} -index {{i}} - isFirst {{f}} - isLast {{l}}- isOdd {{o}} - isEven {{e}}</p>
</div>
`,
styleUrls: ['./directives.component.css']
})
export class DirectivesComponent implements OnInit {
constructor() { }
ngOnInit() {
}
public componentName :string = "DIRECTIVES";
public color = "red";
public names = ["Saman","Kasun","Suresh"];
}
Comments
Post a Comment