[英]Angular 4: How to access element inside ng-template
I have a view which holds ng template for MD-Dialog. 我有一个视图,其中包含MD-Dialog的ng模板。
<ng-template #template>
<h2 md-dialog-title>{{title}}</h2>
<div md-dialog-content #content></div>
</ng-template>
Where I have to replace #content with a dynamic component. 我必须用动态组件替换#content。
corresponding component class is, 对应的组件类是
export class CustomDialogComponent implements OnInit, AfterViewInit {
title: string;
@ViewChild('content', { read: ViewContainerRef }) container;
@ViewChild('template') template: TemplateRef<any>;
constructor(public dialog: MdDialog,
private componentFactoryResolver: ComponentFactoryResolver) { }
ngOnInit() {
}
open(component: any, options: any): void {
this.title = options.title;
console.log(this.container)
const dialogRef = this.dialog.open(this.template, options);
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
this.container.clear();
const comp = this.container.createComponent(componentFactory);
comp.instance.setData(options.data);
}
close() {
this.dialog.closeAll();
}
ngAfterViewInit() {
console.log(this.container)
}
}
But I get undefined for this.container in method open(). 但是我在open()方法中没有为此this.container定义。 Please help. 请帮忙。
只有在初始化视图时,模板内部的模板才可访问。因此,在角度8之后,使用ViewChild时,可以使用参数{static: false}
这样可以在初始化视图时使用内部模板的实例
@Viewchild('content', {static: false}) innerConttent: TemplateRef<any>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.