Reputation: 2277
I don't understand the behavior in which I cannot set @Input() value multiple times for a component.
for example, I have a component
export class AComponent {
private _value: string;
@Input()
set value(v: string) {
console.log(`set value : ${v}`);
this._value = v;
}
get value() {
return this._value;
}
}
and in another component, I try to set multiple times value
ngOnInit() {
this.value = "1";
this.value = "2";
}
but it affects only the last value (on the console I see only - set value: 2).
But if I use the setTimeout function it works correctly (I see two values on the console).
ngOnInit() {
this.setValue("1 timeout");
this.setValue("2 timeout");
}
setValue(v: string) {
setTimeout(() => {
this.value = v;
}, 0);
}
Why do I need this behavior? Because I'd like to set a progress spinner before the request to the server and after that disable the progress spinner.
toClick(event) {
// set value before request to server
// for example to set a progress spinner
this.value = "1";
// some async request to server - you get a Promise or an Observable
// set value after request in .then( ) or in subscribe( )
// for example to disable a progress spinner
this.value = "2";
}
Could someone explain this behavior?
Upvotes: 1
Views: 895
Reputation: 2065
Angular uses ChangeDetection System in order to detect the changes and reflect them on the affected views and components, as far as i know, change detection is triggered after each Asynchronous task which includes:
once this async task finishes, it check the previous values for attributes and the current values. In your example, when you click somewhere and trigger toClick method, it waits until the method execution ends and trigger changeDetection, so it will consider the final value for your variable which is "2".
if you run setTimeout inside your toClick method, its new async task, so we have two rounds for ChangeDetection system, each round will reflect the changes for the two values "1" and "2".
Upvotes: 2