如何在angular4中使用TemplateRef的createEmbeddedView方法?
我开始学习Angular中的DOM操作,注意templateRef及其方法createEmbeddedView。我更想了解这种方法。现在我的问题是,如何使用这个方法的createEmbeddedView如何在angular4中使用TemplateRef的createEmbeddedView方法?,angular,angular-template,Angular,Angular Template,我开始学习Angular中的DOM操作,注意templateRef及其方法createEmbeddedView。我更想了解这种方法。现在我的问题是,如何使用这个方法的createEmbeddedView @Component({ selector: 'app-root', template: ` <ng-template #template> </ng-template> ` }) export class AppComponent implements A
@Component({
selector: 'app-root',
template: `
<ng-template #template>
</ng-template>
`
})
export class AppComponent implements AfterViewChecked {
@ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
constructor() { }
ngAfterViewChecked() {
this._template.createEmbeddedView('this is a embedded view')
}
}
@组件({
选择器:'应用程序根',
模板:`
`
})
导出类AppComponent实现AfterViewChecked{
@ViewChild('template',{read:TemplateRef})\u template:TemplateRef;
构造函数(){}
ngAfterViewChecked(){
此.\u template.createEmbeddedView('这是一个嵌入式视图')
}
}
您可以使用createEmbeddedView
方法创建嵌入式视图,然后通过ViewContainerRef
将该视图附加到DOM:
@Component({
selector: 'app-root',
template: `
<ng-template #template let-name='fromContext'><div>{{name}}</ng-template>
<ng-container #vc></ng-container>
`
})
export class AppComponent implements AfterViewChecked {
@ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;
constructor() { }
ngAfterViewChecked() {
const view = this._template.createEmbeddedView({fromContext: 'John'});
this.vc.insert(view);
}
}
上下文是一个具有属性的对象,您可以通过let-
绑定访问这些属性
要了解更多信息,请阅读并查看。上下文类型是什么,是否为字符串?vc代表什么,是viewContainerRef吗?是的,我理解,但我的问题是什么是您在代码中也提到的“上下文”类型。它是一个接受值的字符串吗element@LijinJohn,我刚刚添加了一个在template@LijinDurairaj“我的答案还有什么不清楚的地方吗?”@LijinDurairaj如果这回答了你的问题,请将此标记为答案。
ngAfterViewChecked() {
this.vc.createEmbeddedView(this._template, {fromContext: 'John'});
}