Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i access in reactive form async data in template to set selected value for mat-select

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<form *ngIf="menuData$ | async; else loading" [formGroup]="form">
<mat-form-field class="col-md-8"  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.

>Solution :

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">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading