【问题标题】:ViewChild: ERROR TypeError: "this.child is undefined"ViewChild:错误类型错误:“this.child 未定义”
【发布时间】:2019-06-09 18:08:12
【问题描述】:

在 Angular 7 中,我有一个包含子组件的组件。但是,我想获取该子组件的副本以在父组件中使用、调用其函数或其他任何内容。

子组件:

@Component({
  selector: 'app-child',
  template: `
    <h1>child</h1>
  `,
})
export class ChildComponent {
       name = "child";
       constructor(){}
}

父组件:

import { ChildComponent } from  './table/child.component';

@Component({
  selector: 'app-parent',
  template: `
    <h1>parent</h1>
    <app-child></app-child>
  `,
})
export class  ParentComponent implements AfterViewInit, OnInit{
  @ViewChild(ChildComponent) child: ChildComponent;

  ngAfterViewInit(){
   console.log(' ngAfterViewInit() : ', this.child.name);
  }

}

我实际上使用了一个模板 CoreUi https://github.com/coreui/coreui-free-angular-admin-template,这个模板是不同的,因为每个组件都应该有自己的(模块和路由)。

子组件:src/App/views/test/table/child.component.ts

父组件:src/App/views/test/parent.component.ts

请帮我解决这个问题,

谢谢

【问题讨论】:

  • 请你也分享你的html代码吗?
  • 您的代码是正确的,但我认为您的子组件尚未加载,我需要查看您的 HTML 代码。
  • 如果@debabrata-paul-chowdhury 正确,请尝试使用setTimeout(() =&gt; console.log(' ngAfterViewInit() : ', this.child.name),500)。在某些情况下,取决于您的子组件被实例化的位置(例如,在一个对话框中并且您的子组件是动态实例化的),这需要更长的等待时间。如果这是你的情况,setTimeout 就足够了,你可以校准它的延迟。

标签: angular core-ui


【解决方案1】:

我想这是因为子组件还没有渲染,你可以使用ngAfterContentInit。

这个生命周期钩子应该只在孩子被绘制后被触发,然后你应该能够获得参考。

import { ChildComponent } from  './table/child.component';

export class  ParentComponent implements ngAfterContentInit, OnInit{
  @ViewChild(ChildComponent) child: ChildComponent;

   ngAfterContentInit(){
   console.log(' ngAfterContentInit() : ', this.child.name);
  }

}

如果有任何帮助,请告诉我。

【讨论】:

  • 感谢您的帮助,但实际上,它并不能解决我的问题。因为当我尝试它时,我得到了同样的错误!
  • 我也不知道怎么做,但我正在尝试查看这个模板的结构,以解决我认为的问题。拜托,你能给出任何可以帮助我解决它的建议吗
  • 修改自己的模块后,您的解决方案已经正常工作了,谢谢大佬。
【解决方案2】:

为确保您的孩子已加载,请使用 ViewChildren(),并订阅更改。

【讨论】:

    猜你喜欢
    • 2017-12-22
    • 2019-10-31
    • 2019-07-20
    • 2016-08-07
    • 2019-01-07
    • 2020-01-28
    • 2021-10-24
    • 2014-10-17
    • 2022-01-10
    相关资源
    最近更新 更多