farcasmihai91
4/20/2018 - 8:46 PM

Angular - View Container Ref

export class ViewContainerRefWidgetComponent implements AfterViewInit {
  widgetTitle = ViewContainerRef;
  @ViewChild('vcr1', {read: ViewContainerRef}) vcr1: ViewContainerRef<any>;
  @ViewChild('vcr2', {read: ViewContainerRef}) vcr2: ViewContainerRef<any>;
  @ViewChild('t1') t1: TemplateRef<any>;
  @ViewChild('t2') t2: TemplateRef<any>;
  @ViewChild('t3') t3: TemplateRef<any>;

  addTemplate(): void {
    this.vcr1.createEmbeddedView(this.t1);
  }

  addTemplate2() {
    this.vcr2.createEmbeddedView(this.t2);
  }

  vcr1IsEmpty() {
    return this.vcr1.length === 0;
  }
  clearVCR1() {
    this.vcr1.clear();
  }
}

// the component template
// <h1>ViewContainerRef</h1>
// <button (clear)="addTemplate1()">Add Template 1</button>
// <button (clear)="addTemplate1()">Add Template 2</button>
// <button [disabled]="vcr1IsEmpty()" (click)="ClearVCR1()">Clear VCR1</button>

// <hr />
// <div #vcr1></div>
// <hr />
// <div #vcr2></div>

// <ng-template #t1>Template 1 <br /></ng-template>
// <ng-template #t2>Template 1 <br /></ng-template>
// <ng-template #t3>Template 1 <br /></ng-template>