我遇到一个问题,即我的ViewChild.nativeElement
在所有生命周期挂钩中都为空。我的组件看起来像这样:
@Component({
selector: 'connector-component',
template: `
<ng-container>
<ng-content></ng-content>
</ng-container>
`
})
export class ConnectorComponent implements AfterContentInit {
@ContentChild('ccdComponent') ccdComponent: ElementRef;
ngAfterContentInit() {
console.log(this.ccdComponent); // works as expected
console.log(this.ccdComponent.nativeElement); // null :(
}
}
该组件将被这样调用:
<connector-component>
<ccd-search #ccdComponent>
</ccd-search-component>
</connector-component>
我想确定的是#ccdComponent
的标记名-在这种情况下为ccd-search
。我们可以保证connector-component
将包含带有标签#ccdComponent
的子组件。而且,无论如何,ElementRef
填充在生命周期挂钩中,但是nativeElement
为空。
我该怎么做?
答案 0 :(得分:0)
@ContentChild
的默认行为是读取 component 实例。因此,<ccd-search>
的实例没有名为nativeElement
的属性,因此该值将始终为 undefined 。
您必须告诉查询您要阅读的内容。
@ContentChild('ccdComponent', {read: ElementRef}) ccdComponent: ElementRef;
将在调用ccdComponent
之前设置ngAfterContentInit
的值。
https://angular.io/api/core/ContentChild
我认为我从未见过Angular创建一个{<1>}对象来包装 undefined 元素。下次您看到ElementRef
未定义。再看一下thing.nativeElement
,并确保它是thing
。 Angular将创建ElementRef
或不会创建。{p>