Angular2 Structural Directive
پنجشنبه, ۲۴ فروردين ۱۳۹۶، ۰۲:۱۱ ب.ظ
ViewContainer (Structural Directives)
Since Angular 2* we can use ViewContainer simplifying structural directives authoring like ngIf.
We don’t require to manually deal with creating the View, setting up the resulting DOM elements and connecting change detection. The ViewContainer will deal with these for us resulting in the following code.
import {ViewContainerRef, TemplateRef} from '@angular/core' @Directive({ selector: '[myIf]' }) export class myIf { private view; constructor(private container: ViewContainerRef, private template: TemplateRef<any>) { } @Input() set myIf(expression: boolean) { if (expression) { this.view = this.container.createEmbeddedView(this.template); } else { this.view.destroy(); } }; } |
Let’s see an example of how we would use it
<div>
<h2 *myIf="show">Hello {{name}}</h2> <-- EmbeddedView
<button (click)="show=!show">
Toggle
</button>
</div>
This is syntax sugar for
<template [myIf]="show"> <-- ViewContainerRef
<h2>Hello {{name}}</h2> <-- TemplateRef
</template>
۹۶/۰۱/۲۴