When creating a component in angular 2 that has inputs attributes via @Input, how can I get an observable from the changes made to that attribute @Input (not to be confused with user form input).
export class ExampleComponent implement OnChanges{
@Input() userObject: User;
ngOnChanges(changes: any): void{
// Validate that its the 'userObject' property first
this.doStuff()
}
}
In practice, I would like to merge the Observable changes of the userObject with the Observable changes of other things to have a fluent change reaction pattern.
export class ExampleComponent implement OnChanges{
@Input() userObject: User;
constructor():{
userObject.valueChanges.subscribe(x=>{ this.doStuff() });
}
}
I found out the that BehaviorSubject class enables this scenario the best. Instead of creating a separate backend field, you can use the BehaviorSubject's getValue function to peak at the current value. Then use the backing BehaviorSubject to view as an observable for changes.
export class ExampleComponent{
private _userObject: BehaviorSubject<User> = new BehaviorSubject<User>(null);
@Input()
set userObject(value: User): { this._userObject.next(value); }
get userObject(): User { return this._userObject.getValue(); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With