Last active
November 1, 2017 20:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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