在模板中的对应元素显示后,获取@viewchild
的最优雅的方法是什么?
下面是一个例子。还提供柱塞。
component.template.html:
<div id="layout" *ngIf="display">
<div #contentPlaceholder></div>
</div>
component.component.ts:
export class AppComponent {
display = false;
@ViewChild('contentPlaceholder', { read: ViewContainerRef }) viewContainerRef;
show() {
this.display = true;
console.log(this.viewContainerRef); // undefined
setTimeout(() => {
console.log(this.viewContainerRef); // OK
}, 1);
}
}
我有一个默认情况下隐藏其内容的组件。当有人调用show()
方法时,它将变得可见。但是,在Angular 2更改检测完成之前,我不能引用viewcontainerref
。我通常将所有必需的操作包装到setTimeout(()=>{},1)
中,如上图所示。有没有更正确的方法?
我知道有一个带有ngAfterViewChecked
的选项,但是它导致了太多无用的调用。
为ViewChild使用setter:
private contentPlaceholder: ElementRef;
@ViewChild('contentPlaceholder') set content(content: ElementRef) {
if(content) { // initially setter gets called with undefined
this.contentPlaceholder = content;
}
}
一旦*ngif
变为true
时,就会使用元素引用调用setter。
注意,对于Angular 8,您必须确保设置{static:false}
,这是其他Angular版本的默认设置:
@ViewChild('contentPlaceholder', { static: false })
注意:如果contentPlaceholder是一个组件,您可以将ElementRef更改为您的组件类:
private contentPlaceholder: MyCustomComponent;
@ViewChild('contentPlaceholder') set content(content: MyCustomComponent) {
if(content) { // initially setter gets called with undefined
this.contentPlaceholder = content;
}
}