1
votes

I'm patching values to field in reactive form using the below code :

editPat(patient: Patient) {
    this.regForm.patchValue({
        _id: patient._id,
        firstName: patient.firstName,
        lastName: patient.lastName,
        disease: patient.disease,
        department: patient.department,
        doctor: patient.doctor
    });
}

In this function department and doctor formcontrols are containing select field and value does not appear in select . The value i'm assigning to formcontrol here that is value of option..

problem how can i assign value to select through patchValue .Please help me


HTML:

<div class="form-group ">
    <label for="department">Department</label>
    <select class="form-control" formControlName="department">
        <option *ngFor="let department of departments"
                value="{{ department._id }}">{{ department.Name }}</option>
    </select>
</div>

Actually i'm using this code and after saving data in db (i.e id) when i tried to patch value (for update option) other fields works but for select its does not work..

1
hi Farhat Mustafa first you do not need to patch one by one property, you can simple patch your patient object into form by using this line Object.assign(this.regForm, patient); please share screen or code for your select tag html - kushal shah
please checkout y updated question @kushalshah and Object.assign isn't builtin function but patchValue in angular 8 - Farhat Mustafa
Farhat Mustafa bind value in option like this [value]="department._id" let me know it's useful or not? - kushal shah
Farhat Mustafa have you tried with Object.assign() function ? I am just asking - kushal shah
yes i tried but it does not work and [value] isn't useful - Farhat Mustafa

1 Answers

0
votes

You can either try the another way to patch the value ,
UPDATED CODE
HTML file

<div class="form-group ">
    <label for="department">Department</label>
    <select (change)="patchValue($event.target.value)" class="form-control" formControlName="department">
        <option *ngFor="let department of departments"
                value="{{ department._id }}">{{ department.Name }}</option>
    </select>
</div>

.ts file

patchValue(value){
    this.regForm.patchValue({
        department : value
    });
    this.regForm.get('department').updateValueAndValidity();
    console.log(this.regForm.value);
}

Checkout my updated code .