I decided to create a new observable using the values emitted by the FormControls.valueChanges
observable. This creation of the observable takes place within the ngOnInit
method in the following manner:
ngOnInit(): void {
this.myObservable$ = combineLatest([
this.formControl1.valueChanges,
this.formControl2.valueChanges
]).pipe(
map(([v1, v2]) => parseInt(v1, 10) + parseInt(v2, 10))
);
this.isLoading = true;
this.loadData().subscribe({
next: result => {
this.formControl1.setValue(result[0]);
this.formControl2.setValue(result[1]);
this.isLoading = false;
},
});
}
The subscription to the observable occurs after setting isLoading
to false:
<div *ngIf="!isLoading">{{ myObservable$ | async }}</div>
Therefore, in this scenario, myObservable$
will only start emitting values once formControl1
and formControl2
are manually changed, since the first emissions of valueChanges
happen before subscribing to this observable.
A more elaborate solution could be crafted for this situation:
this.myObservable$ = defer(() => combineLatest([
this.formControl1.valueChanges.pipe(startWith(this.formControl1.value)),
this.formControl2.valueChanges.pipe(startWith(this.formControl2.value))
])).pipe(
map(([v1, v2]) => parseInt(v1, 10) + parseInt(v2, 10))
);
Is there perhaps a more elegant solution to tackle this?
( is the StackBlitz link for a basic example)