یادداشتهای علی انصاری

Angular2 Structural Directive

پنجشنبه, ۲۴ فروردين ۱۳۹۶، ۰۲:۱۱ ب.ظ

ViewContainer (Structural Directives)

Reference


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>
موافقین ۰ مخالفین ۰ ۹۶/۰۱/۲۴
علی انصاری

نظرات  (۰)

هیچ نظری هنوز ثبت نشده است

ارسال نظر

ارسال نظر آزاد است، اما اگر قبلا در بیان ثبت نام کرده اید می توانید ابتدا وارد شوید.
شما میتوانید از این تگهای html استفاده کنید:
<b> یا <strong>، <em> یا <i>، <u>، <strike> یا <s>، <sup>، <sub>، <blockquote>، <code>، <pre>، <hr>، <br>، <p>، <a href="" title="">، <span style="">، <div align="">
تجدید کد امنیتی