【发布时间】:2019-08-14 16:42:50
【问题描述】:
下面的屏幕有 4 个按钮,用于完成有关在组件之间传递数据的教程 (Sharing Data Between Angular Components - Four Methods)。
@ViewChild 部分有问题。四个按钮下方有一个路由器链接,每个按钮上都会填充一个相关组件。
当我单击@ViewChild 按钮时,组件显示但消息未填充,它是空的。
当我再次单击@ViewChild 按钮时,消息按预期填充。
我确定这不是@ViewChild 的预期结果。所以我需要知道它为什么这样做以及如何更正它,以便在第一次点击时看到消息。
教程说:'我们需要实现 AfterViewInit 生命周期挂钩来接收来自孩子的数据',我已经完成了。
以下是我的父子代码。
家长
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child/child.component';
@Component({
selector: 'app-data-view-child',
templateUrl: './data-view-child.component.html',
styleUrls: ['./data-view-child.component.scss']
})
export class DataViewChildComponent implements AfterViewInit {
@ViewChild(ChildComponent, { static: false }) child;
constructor() { }
message: string;
ngAfterViewInit() {
this.message = this.child.message
}
}
儿童
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent {
message = 'Hola Mundo!';
constructor() { }
}
父模板
<div class="parent-card">
<h1>I am the Parent component</h1>
<h2 class="tac">Message: {{ message }}</h2>
<app-child></app-child>
</div>
请告诉我为什么在第一次点击时该消息不可用。
【问题讨论】:
-
父模板是什么样子的
-
现在将其添加到问题中。
-
您是否在日志中看到“检查后表达式已更改”之类的错误?
-
控制台中没有显示错误。
-
您是在开发模式还是产品模式下运行?错误将在 prod 模式下被抑制