[英]Child component value not setting in Angular 2?
So I have my child component's value marked like so: 因此,我将子组件的值标记为:
@Input flag;
And then in the particular method I have: 然后在特定的方法中,我有:
myParentComponent.flag = true;
Then in the html of the parent component I have: 然后在父组件的html中,我有:
<app-childComponent-template [flag] = flag ></app-childComponent-template>
I'm using Chrome's inspection tool to watch the console where I'm logging the changes. 我正在使用Chrome的检查工具来查看记录更改的控制台。 When I set the flag to true in the child component it works, however, it won't carry over to the parent component and I can't figure out why.
但是,当我在子组件中将标志设置为true时,它会起作用,但是不会继承到父组件,因此我不知道为什么。 I've gone through this documentation ( https://angular.io/guide/component-interaction ) multiple times but everything seems to match up accordingly.
我已经多次阅读了本文档( https://angular.io/guide/component-interaction ),但似乎一切都相符了。
Thank you! 谢谢!
The syntax [flag]
indicates that it's a one-way data binding: The parent will push changes to flag
to the child. 语法
[flag]
表示这是一种单向数据绑定:父级将把更改推送给子级flag
。 But changing the child's @Input flag
variable will not emit a change to the parent. 但是更改子项的
@Input flag
变量不会向父项发出更改。
In order to do that, you need to use an @Output
in the child component: 为此,您需要在子组件中使用
@Output
:
@Input('flag') flag;
@Output('flag') flagChanged = new EventEmitter<boolean>();
Then, to inform the parent that the flag has changed, emit an event from the child component: 然后,要通知父标志已更改,请从子组件中发出一个事件:
this.flagChanged.emit(newFlagValue);
Finally, to be informed of changes in the parent component: 最后,要通知父组件中的更改:
<app-childComponent-template [flag]="flag" (flag)="onFlagChanged($event)"></app-childComponent-template>
onFlagChanged(newValue) {
alert(`New flag value: ${newValue}`);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.