【发布时间】:2020-03-25 11:26:48
【问题描述】:
由于某种原因,我的 Angular 8 应用程序中的 @ViewChild 无法“未定义”工作。我在 html 文件中这样定义它:
<div class="container">
<div class="row h-100">
<kendo-splitter orientation="vertical">
<kendo-splitter-pane>
<kendo-splitter>
<kendo-splitter-pane>
...
</kendo-splitter-pane>
<kendo-splitter-pane>
<div>
<myComponent #myComp ....> </<myComponent> // ViewChild id here
</div>
</kendo-splitter-pane>
</kendo-splitter>
</kendo-splitter-pane>
</kendo-splitter>
在 ts 文件中,我尝试了以下操作,但都返回 undefined:
@ViewChild(myComponent, { static: true }) child: myComponent;
@ViewChild('myComp', { static: false }) child: myComponent;
- @ViewChild('myComp', {static:true}) child: ElementRef;
我使用了 ngAfterViewInit 但仍然未定义。是不是因为myCompnent被很多html元素包裹了?
【问题讨论】:
-
@ViewChild(myComponent, { static: true }) child: myComponent;这应该是理想的工作,你有一个 stackblitz 链接来演示这个问题吗? -
您能否在您的 myComponent 组件中检索 ngOnInit() 函数中的值?
-
我知道这听起来像是在开玩笑,但是当您尝试访问它时,请确保该元素在 DOM 中(假设您在某些情况下使用 *ngIf)