Roman Šimík
Roman Šimík

Reputation: 900

Angular deselect all options in multiple select

Goal is that, when I call myMethod(), I want to have all options unselected.

Currently when I call myMethod() it will deselect only the last option, but the other remain selected if they have been selected.

Solutions:

HTML

<select multiple>
    <option *ngFor="let user of users" 
            value="{{user.id}}" 
            [selected]="usersSelected">{{user.name}}
    </option>
</select>

Component

usersSelected: boolean = false;

myMethod(): void {
    this.usersSelected = false;
}

Thanks for any help.

Upvotes: 1

Views: 5378

Answers (1)

Martin Ad&#225;mek
Martin Ad&#225;mek

Reputation: 18359

You should use [(ngModel)] so you can control the value. Note that its multiple select, so you should use array, not just scalar value.

usersSelected = [];

myMethod(): void {
  this.usersSelected = [];
}

And in your template:

<select multiple [(ngModel)]="usersSelected">
  <option *ngFor="let user of users" [ngValue]="user.id">{{user.name}}</option>
</select>

Working example: https://stackblitz.com/edit/angular-c9y1jm

Upvotes: 1

Related Questions