Angular select options control does not reset ngModel value automatically even if I empty the array of options

Issue

I have a very basic select-option input control in Angular 8. User selects one item from dropdown and it’s reflected correctly in dropdown as well as in ngModel variable.

But if I empty the source array programmatically, dropdown is still keeping the old value in ngModel and angular validation shows the control to be in a “valid” state. However, nothing is shown as selected in the dropdown as the source array is now empty.

I am expecting that ngModel should be reset and control should be in invalid state as nothing is selected now.

Is my expectation wrong? Or am I doing something wrong?

Following is a complete example to reproduce the behavior:

Angular 8: StackBlitz

Update 1:

I have created an example in Angular 1 which is working exactly as I expected. AngularJS clears the model value if there is no matching option found in options array. My point is that if dropdown is visible empty then user would assume nothing is selected. However in case of Angular2+, its holding old model value behind the scene.

Angular 1: StackBlitz

Solution

I think in your expectation has something wrong, no need to empty the dropdown list. Just need to set the ngModel to empty value like this model.power = ''.

So since you are using template driven form here also you could reset the form state by using the reset() method of the form (heroForm) like bellow, no need to change anything:

<button type="button" class="btn btn-default" (click)="heroForm.reset()">Clear Array</button>

Working DEMO

If you need to empty the dropdown and also need get the form state to invalid state use like bellow

<button type="button" class="btn btn-default" (click)="powers=[]; model.power=''">Clear Array</button>

According to your updated question you could achieve it like bellow:

<div class="form-group">
        <label for="power">Hero Power</label>
        <select class="form-control" id="power"
                required
                [(ngModel)]="model.power" name="power"
                #power="ngModel">
          <option [ngValue]="null">All</option>
          <option *ngFor="let pow of powers" [ngValue]="pow">{{pow}}</option>
        </select>
      </div>

      <button type="button" class="btn btn-default" (click)="powers=[]; model.power=null">Clear Array</button>

Working DEMO

Answered By – coder

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.