【发布时间】:2020-05-22 21:19:19
【问题描述】:
我有父子组件通信,我想在子组件中启动一个方法,该方法应该打开一个模式并传递数据。当我使用 ViewChild 从父调用函数时,子方法组件中的变量返回 null,但变量内部应该有数据。当我在子组件中触发相同的函数时,数据是可用的,但从父组件调用时不是这种情况。缺少什么以及为什么从父组件启动时我看不到子组件中的数据?
父.html
<button (click)="openModal()">New</button>
<child><child>
父.ts
import { FilterComponent } from './../filter/filter.component';
@ViewChild(FilterComponent) filterComponent: FilterComponent;
openModal(){
this.filterComponent.openModal(); // when fired from here, the function in the child component fires, but the variable inside it returns null
}
child.html
<button (click)="openModal()">New</button>
<modal><modal>
child.ts
openModal(){
modalVisible = true;
console.log(this.filter) returns null; when fired from parent component
console.log(this.filter) returns "filter data"; when fired within the component
}
【问题讨论】:
-
我很欣赏添加的代码,但恐怕这不足以确定什么是错的。您能否分享足够的代码来重现该问题?最好使用 StackBlitz 示例。
-
当您在父母中使用 viewchild 时,它不会初始化子组件.. 简单来说,它不会调用它的构造函数.. 您可以在父组件中使用 afterviewchild 生命周期进行确认...而您在未初始化的子组件中使用 this.filter ..这些这是代码中的问题陈述...它将始终为空..如果您想要值,您必须从父组件初始化
标签: javascript angular viewchild