Update parent component property from child component in Angular 2
You need to use 2 way data-binding.
@Input()
is one way data-binding.
to enable 2 way data-binding you need to add an @Output()
corresponding to the property, with a "Change" suffix
@Input() getSearchStatus: boolean;
@Output() getSearchStatusChange = new EventEmitter<boolean>();
when you want to publish the change made to your property to the parent, you need to notify the parent with:
this.getSearchStatusChange.emit(newValue)
and in the parent you need to use the banana-in-a-box notation for that property:
[(getSearchStatus)]="myBoundProperty"
you can also bind to the property and trigger a callback when it changes in child:
[getSearchStatus]="myBoundProperty" (getSearchStatusChange)="myCrazyCallback($event)"
see the plnkr
Another approach: use rxjs/BehaviorSubject to pass status between different components.
Here's the plunkr.
I name subject with a suffix 'Rxx', so the BehaviorSubject for searchStatus will be searchStatusRxx.
- initialize it in parent component like
searchStatusRxx = new BehaviorSubject(false);
, - pass it to child component using @Input
- in child template, you do async pipe.
- in both parent and child, you do
searchStatusRxx.next(value)
to change the latest value.