darekf77
4/6/2017 - 5:42 PM

An example to show the way of injecting template into Angular2 component dynamically

An example to show the way of injecting template into Angular2 component dynamically

import { NgFor } from '@angular/common'
import { Component, QueryList, TemplateRef, ViewChild, ViewChildren, ViewContainerRef } from '@angular/core'

@Component({
  directives: [
    NgFor
  ],
  selector: 'component',
  template: `
    <ul><li #item *ngFor="let number of list">{{number}}</li></ul>
    
    <template #template>
      <li>template</li>
    </template>
  `
})
class _Component {

  @ViewChild('template')
  template: TemplateRef<any>

  @ViewChildren('item', { read: ViewContainerRef })
  items: QueryList<ViewContainerRef>

  list: number[] = [0, 1, 2, 3, 4]

  ngAfterViewInit() {
    setTimeout(() => {
      this.items.first.createEmbeddedView(this.template)
    }, 1000)
  }
  
}