Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mr-pinzhang/ca9ee3eb89e0fcb46eb4e3909f88407b to your computer and use it in GitHub Desktop.
Save mr-pinzhang/ca9ee3eb89e0fcb46eb4e3909f88407b to your computer and use it in GitHub Desktop.
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment