I have a form which uses a query that is an observable and feches data from an API to allow the user to edit that data. Below is the code i use to fetch the data and I can populate all the fields on the form fine which i do via the patchValue.
menuData$: Observable<IMenu>;
ngOnInit(){
this.menuData$ = this.menuService.fetchMenuItem(docId).pipe(
tap(menuData => this.form.patchValue(menuData)),
tap(menuData => console.log(menuData)),
)
}
The problem i am running into is that in my case the parents field of menuData holds the value for my mat-select but i cant get it to set it correctly.
The code in my html template looks like this
<form *ngIf="menuData$ | async; else loading" [formGroup]="form">
<mat-form-field ngDefaultControl label=" " formControlName="parent">
<mat-label>Parent</mat-label>
<mat-select [(value)]="parent">
<mat-option value="" aria-selected="true" selected> --Select Parent -- </mat-option>
<mat-option *ngFor="let parent of menuParents$ | async" [value]="parent._id">
{{ parent.name}}
</mat-option>
</mat-select>
</mat-form-field>
</form>
So my question is how can i set/bind the value of my mat-select to what i got from my query. I was able to do it by defining a new variable testValue: string and then in the pipe set the value like tap(menuData => (this.testValue = menuData.parent)). Even so this works i dont think that is the best or cleanest way to achive this.
CodePudding user response:
Use as
within the *ngIf
and then reference that object from the <mat-select>
:
<form *ngIf="menuData$ | async as menuData; else loading" [formGroup]="form">
...
<mat-select [(value)]="menuData.parent">