resetting angular reactive form is not updating the select option

Viewed 6055

I have created an angular form using materialize-css. Here is the HTML

<form [formGroup]="addFeedForm" (ngSubmit)="addFeed(addFeedForm.value)" class="col s12">
    <div class="row">
        <div class="input-field col m6 s12">
            <select formControlName="departmentId" #feedDepartment>
                <option value=0>General</option>
                <option [value]="department.id" *ngFor="let department of departmentList">{{department.name}}</option>
            </select>
            <label>Department</label>
        </div>

        <div>
            <button type="button" class="btn waves-effect waves-light col s3 offset-s5" (click)="resetAddFeedForm()">Reset</button>

            <button type="submit" [disabled]="!addFeedForm.valid" class="btn waves-effect waves-light col s3 offset-s1">Add</button>

        </div>
    </div>
</form>

And this is how I have created the angular form

this.addFeedForm = new FormGroup({
      departmentId: new FormControl(0,Validators.compose([Validators.required])),
});

And when I submit I do

addFeed(data: any): void {
    console.log(data);

    this.addFeedForm.reset({    departmentId: 0    });
}

If I change the department select option to something else and submit and reset the form by setting departmentId to be 0 then "General" should be selected in the select option.

It is not updating on the UI but on the console, it sets departmentId to 0.

The UI behaviour is like enter image description here

on the UI selected option is different but on the console departmentId is 0

Update : This is the stackblitz

https://stackblitz.com/edit/angular-tchftw

4 Answers

update your form control using

 addFeed(data: any): void {
     console.log(data);
     this.addFeedForm.patchValue({departmentId: '0'});
 }

Or you can also use

this.addFeedForm.controls['departmentId'].setValue('0');

Try this way

addFeed(data: any): void {     
   this.addFeedForm.patchValue({departmentId: [0]});
}

PatchValue will always works to re-set the value in angular. It always works for me.

put type reset on button it will work : <button type="reset" class="btn waves-effect waves-light col s3 offset-s5" (click)="resetAddFeedForm()">Reset</button> working example : stackblitz live example

I am also face the same problem like above said, so I wish to share my workaround for the same

template

<select formControlName="departmentId" #feedDepartment>
    <option selected [ngValue]=null disabled >General</option>
    <option [value]="department.id" *ngFor="let department of departmentList">{{department.name}}</option>
 </select>

typescript

this.addFeedForm = this.fb.group({
  departmentId: [null,Validators.required]
})

onResetForm(){
this.addFeedForm.reset();
}

In reactive form: I initialize the departmentId formControlName with null, so i changed my first select option accordingly in template also. hence i got the expected behavior

Related