未在Angular 2中设置子组件值? [英] Child component value not setting in Angular 2?

查看:58
本文介绍了未在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;

然后在父组件的html中:

Then in the html of the parent component I have:

<app-childComponent-template [flag] = flag ></app-childComponent-template>

我正在使用Chrome的检查工具来查看记录更改的控制台.但是,当我在子组件中将标志设置为true时,它会起作用,但是它不会继承到父组件,因此我无法弄清原因.我已经阅读了这份文档( https://angular.io/guide/component-interaction)多次,但一切似乎都相符.

I'm using Chrome's inspection tool to watch the console where I'm logging the changes. 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. I've gone through this documentation (https://angular.io/guide/component-interaction) multiple times but everything seems to match up accordingly.

谢谢!

推荐答案

语法 [flag] 表示这是一种单向数据绑定:父级会将更改推送到 flag 给孩子.但是更改子级的 @Input标志变量不会对父级发出更改.

The syntax [flag] indicates that it's a one-way data binding: The parent will push changes to flag to the child. But changing the child's @Input flag variable will not emit a change to the parent.

为此,您需要在子组件中使用 @Output :

In order to do that, you need to use an @Output in the child component:

@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}`);
}

这篇关于未在Angular 2中设置子组件值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆