简体   繁体   English

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

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

I have two components, parent.component.ts and child.component.ts , the template, parent.component.html likes below:我有两个组件, parent.component.tschild.component.ts ,模板, parent.component.html喜欢下面:

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

I bind a constant string good intentionally to demonstrate my concern.我绑定一个字符串常量good有意证明我的担忧。 So, initially, the good string is passed to the child component .因此,最初, good字符串被传递给child component But if I change its value in child.component.ts , like this.status = 'bad';但是如果我在child.component.ts改变它的值,就像this.status = 'bad'; , what will happen? , 会发生什么?

  1. I think the input binding of parent is not synced with the child, since from now on they have different status.我认为父母的输入绑定没有与孩子synced ,因为从现在开始他们有不同的状态。 If I query console.log(this.status) , it will say bad .如果我查询console.log(this.status) ,它会说bad If I want to keep them in sync, I have to use some output bindings.如果我想让它们保持同步,我必须使用一些输出绑定。

  2. How I can do to make sure the input binding still work after the programmatically change.如何确保输入绑定在以编程方式更改后仍然有效。 Say, it changes to bad for one tick , but it changes back to good (automatically) since the binding from parent.比如说,它在一个tick变为bad ,但自从父级绑定后它又变回了good (自动)。

The parent basically doesn't listen to the change in the child component, unless the child component use the parent as an input, like父组件基本上不会监听子组件的变化,除非子组件使用父组件作为输入,比如

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

and in the parent component并在父组件中

this.parent = this

Otherwise, you can create an Output for the status in the children component and the parent component can listen to it否则,您可以为子组件中的状态创建一个输出,父组件可以监听它

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

and

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

so in the parent component, you can add this function所以在父组件中,你可以添加这个功能

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

when you want to emit the change, in the child component, just call当您想发出更改时,在子组件中,只需调用

this.statusEvt.emit(this.status)

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

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