In reactive form, I am using mat-select in a FormArray, for reason that I didn't understand the valueChange response only in the second touch.
this is the method that I am using:
doSomething(i) {
this.form.at(i).valueChanges.pipe(switchMap((categoryId: any) => {
return this.service.getDataByCategoryTypeAndProperty(categoryId, this.propertyId)
})).subscribe(data =>{
this.gatData = data
})
}
<mat-form-field >
<mat-label>Service </mat-label>
<mat-select formControlName="categoryId" (selectionChange)="doSomething(i)" >
<mat-option *ngFor="let category of Categories" [value]="category.categoryId">{{category.categoryName}}</mat-option>
</mat-select>
</mat-form-field>
my question is how valueChanges will respond from the first touch, Thanks
CodePudding user response:
You don't need to mix events with valuechanges. Do either.
Keeping the event looks like this:
doSomething(i) {
this.service.getDataByCategoryTypeAndProperty(this.form.at(i).value, this.propertyId)
.pipe(take(1))
.subscribe(data => this.gatData = data);
}
For keeping the valuechanges, you set up the valuechanges subscription once after init of the form, e.g. in ngOnInit.
CodePudding user response:
The reason is because you're subscribing to the valueChanges
Obsevable
only when selectionChange
event is fired. Then, in the next change the desired action in the subscription callback occours.
Instead, you need to subscribe to valueChanges
right after you create your form. In this way, you'll be able to see your changes subscription effect right on the first change.
No need for the selectionChange
listener at all, since you're already listening to the form changes.
On the other hand, if you insist to use the selectionChange
event, you can use it by utself only and do your action on doSomething
without subscribing to valueChanges
, but then you will loose all the rxjs
logic benefits - such the pipe
you're using there.