简体   繁体   中英

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:

<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. 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.

Thank you!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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