【问题标题】:@ViewChild("childRef") childElementRef -- Cannot read properties of undefined@ViewChild("childRef") childElementRef -- 无法读取未定义的属性
【发布时间】:2021-11-18 21:58:03
【问题描述】:

我试图了解如何在 Angular 应用程序中使用“@ViewChild”,因此我创建了两个组件:parent(基础)和 child,其中包含以下内容代码:

import { Component, ViewChild, AfterViewInit  } from '@angular/core';

@Component({
  selector: 'app-base',
  templateUrl: './base.component.html',
  styleUrls: ['./base.component.css']
})
export class BaseComponent implements AfterViewInit {

  @ViewChild("childRef") childElementRef: any;

  childComponentTitle = 'fake child component title';

  constructor(public router: Router) { }

  ngAfterViewInit(): void {
    this.childComponentTitle = this.childElementRef.childComponentTitle;
  }

  changeChildComponentTitle() {
    this.childElementRef.changeComponentState('actual child component title');
  }
}

<h1>parent (base) component</h1>

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

<h2>{{ childComponentTitle }}</h2>

<button (click)="changeChildComponentTitle()">Show Real Child Component Title</button>

import { Component } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  childComponentTitle: string = "";

  changeComponentState(newState: string) {
    this.childComponentTitle = newState;
  }
}

<h1>child component</h1>

<h2>{{ childComponentTitle }}</h2>

如果我理解正确,一旦我单击按钮(由“BaseComponent”管理),它应该调用“changeComponentState”方法(由“ChildComponent”管理)并且应该显示“实际子组件”页面上的标题。

这确实发生了,但在应用加载时,我立即收到此错误:

ERROR TypeError: Cannot read properties of undefined (reading 'childComponentTitle') at PageoneComponent.ngAfterViewInit

有人可以帮我弄清楚为什么会抛出这个错误吗?

【问题讨论】:

  • 1:您应该会在控制台中看到一个错误,这应该可以帮助您找到问题。 2:似乎您的&lt;app-child 内部没有呈现BaseComponent
  • childElementRef 未定义,因为没有匹配 ViewChild 选择器的元素。使用"childRef" 意味着Angular 将搜索具有模板引用#childRef 的元素,但BaseComponent 的模板中没有
  • 谢谢@p4m。我添加了它。但我仍然得到ERROR TypeError: Cannot read properties of undefined (reading 'childComponentTitle')。这是你的意思吗?

标签: html angular typescript


【解决方案1】:

您应该在尝试访问孩子之前添加一个 if :

  ngAfterViewInit(): void {
    if (this.childElementRef) {
      this.childComponentTitle = this.childElementRef.childComponentTitle;
    }
  }

【讨论】:

  • 这并不能真正解决问题,代码仍然会崩溃,因为childElementRef 未定义
  • 谢谢哈姆扎。您的解决方案引入了一个新错误:ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: fake child component title.
  • 还有Hamza,当我添加if 语句时,应用加载时fake child component title 不会显示。
  • ExpressionChangedAfterItHasBeenCheckedError 是因为您在模板中更新了 parent 中的 childComponentTitle 后才更新它。 Read more about the error
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 2019-08-04
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多