【发布时间】: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:似乎您的
<app-child内部没有呈现BaseComponent -
childElementRef未定义,因为没有匹配ViewChild选择器的元素。使用"childRef"意味着Angular 将搜索具有模板引用#childRef的元素,但BaseComponent的模板中没有 -
谢谢@p4m。我添加了它。但我仍然得到
ERROR TypeError: Cannot read properties of undefined (reading 'childComponentTitle')。这是你的意思吗?
标签: html angular typescript