javascript - 组件初始化后更新父组件@Input属性

标签 javascript angular typescript

我有两个子组件并从父组件引用,我试图在子组件初始化后更新 @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/

相关文章:

javascript - 如何根据屏幕尺寸为元素设置动态宽度?

javascript - 如何过滤 jqGrid 数据而不是网格本身

javascript - Angular2-ngModelChange 中的延迟

javascript - 使用 Angular 从下拉列表中获取选定的值

javascript - 检测一个对象是否穿过 Canvas 中的另一个对象

php - 我如何在 TYPO3 中压缩我的 js/css 文件

html - ngClass 和 CSS 具有所有未设置的意外结果

Angular 4 : What is advantage of injecting HttpClient

typescript - 无法从过滤类型中删除带有 never 的属性以获取剩余的键

oop - Math Parser/Lexer - Token接口(interface)设计