0
votes

I have a Reactive form like below:

this.personForm = this.fb.group({
    firstname: [null, Validators.required],
    lastname: [null, Validators.required],
    home_id: [null],
    home_name: [null, Validators.required],
})

I am retrieving the home list from DB using API and fill the mat-option accordingly, so far is okay, by the way I am displaying home_name value only, inside mat-select:

<mat-form-field class="full-width">
    <mat-select placeholder="Select Home" formControlName="home_name">
        <mat-option *ngFor="let home of homes" [value]="home.name">
            {{ home.name }}
        </mat-option>
    </mat-select>   
</mat-form-field>

now I want to post form values after submit, but I dont know how to update home_id when user clicks on home from dropdown menu ?

I tried:

    <mat-select placeholder="Select Home" 
formControlName="home_name" 
(selectionChange)="setHomeId($event.value)">

but it is giving me home_name only,

I tried to put the same code inside <mat-option> in order to get home object:

<mat-option *ngFor="let home of homes" 
[value]="home_name" 
(selectionChange)="setHomeId($event.value)">

but it seems <mat-option> does not have function : (selectionChange)

2
have you implemented (ngSubmit) ?CruelEngine
yes, of course I have implemented alreadymos
try [ngValue]="home"Chellappan வ
Can't bind to 'ngValue' since it isn't a known property of 'mat-option'.mos

2 Answers

1
votes

I suppose you want to do:

<mat-select placeholder="Select Home" formControlName="home_id">
    <!---value is home.id, show home.name--->
    <mat-option *ngFor="let home of homes" [value]="home.id">{{home.name}}
    </mat-option>
</mat-select>

It's very crazy you need home_name in your personForm. I suppose your database only stores home_id, if so your formGroup must be:

this.personFrom = this.fb.group({
    firstname: [null, Validators.required],
    lastname: [null, Validators.required],
    home_id: [null]
})

NOTE: I don't know if is a type error, but looks like is personForm, not personFrom.

NOTE: Update adding <mat-select formControlName="home_id"..> as @David said.

0
votes

<mat-select (selectionChange)="updateHomeId()" </mat-select>selectionChange Event emitted when the selected value has been changed by the user.

https://material.angular.io/components/select/api

To update reactive form control you can use

updateHomeId() {
 this.personFrom.controls['home_id'].setValue("ID");
}  

https://toddmotto.com/angular-2-form-controls-patch-value-set-value

Hope This Helps.