【问题标题】:@ViewChild returns undefined Angular 8@ViewChild 返回未定义的 Angular 8
【发布时间】: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:

  1. @ViewChild(myComponent, { static: true }) child: myComponent;

  2. @ViewChild('myComp', { static: false }) child: myComponent;

  3. @ViewChild('myComp', {static:true}) child: ElementRef;

我使用了 ngAfterViewInit 但仍然未定义。是不是因为myCompnent被很多html元素包裹了?

【问题讨论】:

  • @ViewChild(myComponent, { static: true }) child: myComponent; 这应该是理想的工作,你有一个 stackblitz 链接来演示这个问题吗?
  • 您能否在您的 myComponent 组件中检索 ngOnInit() 函数中的值?
  • 我知道这听起来像是在开玩笑,但是当您尝试访问它时,请确保该元素在 DOM 中(假设您在某些情况下使用 *ngIf)

标签: html angular viewchild


【解决方案1】:

试试

@ViewChild('myComp', { static: false }) child: myComponent;

或者如果你正在使用

@ViewChild(myComponent, { static: true }) child: myComponent;

确保myComponent 是组件类名而不是选择器(只是为了清楚,因为我无法从示例代码中确认)

【讨论】:

    猜你喜欢
    • 2019-10-19
    • 2017-01-08
    • 2019-07-28
    • 2023-03-05
    • 2016-04-29
    • 2017-03-11
    • 2023-03-21
    • 2019-10-03
    相关资源
    最近更新 更多