【问题标题】:Cannot access @ViewChild property in angular parent component无法访问 Angular 父组件中的 @ViewChild 属性
【发布时间】:2020-06-17 23:33:24
【问题描述】:

child.component.ts

currentPage = 1;

parent.component.ts

export class ParentComponent implements OnInit, AfterViewInit {
  @ViewChild(ChildComponent, {static: false}) child;
  ngAfterViewInit() {
      console.log(this.child.currentPage); // throws error
  }

parent.component.ts

<app-child></app-child>

我尝试设置超时,但也没有用。

ERROR TypeError: Cannot read property 'currentPage' of undefined

我做错了什么?

【问题讨论】:

  • 添加子组件的类型:``` @ViewChild(ChildComponent, {static: false}) child: ChildComponent ``
  • 这也经常发生在我身上。确保孩子不在 ngIf 内并且不在订阅后,如果它是你必须在设置后等待,否则不可用。
  • @shAkur,如果您的 ChildComponent 不在 Angular 中,因为您有一个 *ngIf="condition" -并且条件一开始是错误的,给您一个错误 - 您可以使用 if @987654325 来解决@,傻逼例子stackblitz.com/edit/…
  • 父组件内部子组件的引用确实是有条件的:
    。我的孩子参考在 withoutResults ng 模板中:(

标签: angular components undefined lifecycle viewchild


【解决方案1】:

试试这样:

.html

<app-child #ChildComponent></app-child>

.ts

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

【讨论】:

  • @angular-devkit/core 8.3.23 @angular-devkit/schematics 8.3.23 @angular/cdk 8.2.3 @angular/cli 8.3.23 @ngtools/webpack 8.3.23 @schematics/角度 8.3.23
  • 如果他想操作DOM,他需要指定#ChildComponent,但是在这种情况下,他不需要这个
【解决方案2】:

指定组件名称并在子视图中键入如下

@ViewChild(HelloComponent, {static: false}) hello: HelloComponent;

查看示例stackblitz

【讨论】:

    【解决方案3】:

    有效。

    parent.component.ts

    export class AppComponent implements AfterViewInit {
    
      @ViewChild('child', {static: true})
      child: ChildComponent;
    
      ngAfterViewInit() {
        console.log(this.child.currentPage); // works
      }
    }
    

    parent.component.html

    <app-child #child></app-child>
    

    child.component.ts

    export class ChildComponent {
        currentPage = 1;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-09
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 2019-11-23
      • 2019-01-16
      • 2016-05-17
      • 1970-01-01
      • 2021-08-01
      相关资源
      最近更新 更多