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

۳ مطلب با موضوع «Angular2» ثبت شده است

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

فرض کنید مقدار زیادی داده از طریق web socket  دریافت می کنید و نمی خواهید مرتبا view بروز شود بلکه می خواهید مثلا هر 5 ثانیه view بروز شود:

لینک


constructor(private ref: ChangeDetectorRef) {
    ref.detach();
    setInterval(() => {
      this.ref.detectChanges();
    }, 5000);
  }
۰ نظر موافقین ۰ مخالفین ۰ ۱۴ ارديبهشت ۹۵ ، ۱۵:۵۰
علی انصاری
// at bootstrap
bootstrap(AppComponent, [
  provide(DataService, {useClass: DataService})
]);

// or in component
@Component({
  ...
  providers: [
    provide(DataService, {useClass: DataService})
  ]
})
class AppComponent { }

لینک  و لینک2
۰ نظر موافقین ۰ مخالفین ۰ ۱۲ ارديبهشت ۹۵ ، ۱۳:۴۵
علی انصاری