Question
最优雅的获取方式是什么@ViewChild
显示模板中的相应元素后?
下面是一个例子。还Plunker http://plnkr.co/edit/xAhnVVGckjTHLHXva6wp?p=preview可用的。
组件.template.html:
<div id="layout" *ngIf="display">
<div #contentPlaceholder></div>
</div>
组件.组件.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
,但它会导致太多无用的调用。
答案(笨蛋) http://plnkr.co/edit/myu7qXonmpA2hxxU3SLB?p=preview
对 ViewChild 使用 setter:
private contentPlaceholder: ElementRef;
@ViewChild('contentPlaceholder') set content(content: ElementRef) {
if(content) { // initially setter gets called with undefined
this.contentPlaceholder = content;
}
}
使用元素引用调用 setter 一次*ngIf
变成true
.
注意,对于 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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)