繁体   English   中英

Angular2:如何在以编程方式从子组件更改但未在父绑定中更改后重置输入属性?

[英]Angular2: How to reset input property after it is changed from child component programatically but not changed in parent binding?

我有两个组件, parent.component.tschild.component.ts ,模板, parent.component.html喜欢下面:

<div>
    <child-component [status]="'good'" (click)="changeToBad()"></child-component>
</div>

我绑定一个字符串常量good有意证明我的担忧。 因此,最初, good字符串被传递给child component 但是如果我在child.component.ts改变它的值,就像this.status = 'bad'; , 会发生什么?

  1. 我认为父母的输入绑定没有与孩子synced ,因为从现在开始他们有不同的状态。 如果我查询console.log(this.status) ,它会说bad 如果我想让它们保持同步,我必须使用一些输出绑定。

  2. 如何确保输入绑定在以编程方式更改后仍然有效。 比如说,它在一个tick变为bad ,但自从父级绑定后它又变回了good (自动)。

父组件基本上不会监听子组件的变化,除非子组件使用父组件作为输入,比如

<child-component [parent]="parent"></child-component>

并在父组件中

this.parent = this

否则,您可以为子组件中的状态创建一个输出,父组件可以监听它

@Output() public statusEvt = new EventEmitter<boolean>();

<child-component (statusEvt)="updateStatus($event)"></child-component>

所以在父组件中,你可以添加这个功能

public updateStatus(evt: boolean) {
    this.status = evt;
}

当您想发出更改时,在子组件中,只需调用

this.statusEvt.emit(this.status)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM