我有两个子组件并从父组件引用,我试图在子组件初始化后更新 @Input 对象
.html:
<div>
<app-child-one></app-child-one>
<app-child-two [data]="test"></app-child-two>
<button (click)="onClick()">Clicked</button>
</div>
.ts:
test: string;
onClick() {
this.test = 'Hello World !!';
}
当我单击按钮时,两个子组件都已初始化,单击按钮后如何将数据属性值更新到子组件??
最佳答案
使用@ViewChild你可以实现这一点。添加 id #appChildTwo 中
<div>
<app-child-one></app-child-one>
<app-child-two [data]="test" #appChildTwo></app-child-two>
<button (click)="onClick()">Clicked</button>
</div>
在父级的 .ts 文件中
import { ViewChild } from '@angular/core';
在父级中声明类变量
@ViewChild('appChildTwo') appChildTwo;
点击按钮。通过使用viewchild,我们可以在父组件文件中获取子组件的引用,然后我们可以使用viewchild引用访问子组件的所有公共(public)成员和函数。
onClick() {
this.test = 'Hello World !!';
if(this.appChildTwo)
this.appChildTwo.data= 'Hello World !!';
}
希望这对您有帮助。
关于javascript - 组件初始化后更新父组件@Input属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57049061/