1
votes

I'm using Angular 7.2 to create a select control, as per :

        <mat-select placeholder="Organisation Type" [formControl]="codeSelect" multiple (selectionChange)="changeValue($event)">
          <mat-select-trigger>
            {{codeSelect.value ? codeSelect.value[0] : ''}}
            <span *ngIf="codeSelect.value?.length > 1" class="example-additional-selection">
              (+{{codeSelect.value.length - 1}} {{codeSelect.value?.length === 2 ? 'other' : 'others'}})
            </span>
          </mat-select-trigger>
          <mat-option *ngFor="let org of orgSelectList" [value]="org.orgCode">{{org.orgDisplay}}</mat-option>
        </mat-select>
      </mat-form-field>

This works as intended. I have some code that looks to remove selected items, along the lines of:

let x = this.codeSelect.value.findIndex(x => x == itemToBeRemoved);

if (x > -1) {
  this.codeSelect.value.splice(x, 1);
}

Although this does remove it from the array of selected items. If I go to select new values from the select control, then all of the original items are still selected (i.e. ticked).

How do I clear the selected items?

Following the response from @Maarti my code now works using

let x = this.codeSelect.value.findIndex(x => x == itemToBeRemoved);

if (x > -1) {
  this.codeSelect.value.splice(x, 1);
}

this.codeSelect.setValue(this.codeSelect.value);
1

1 Answers

0
votes

FormControl.value is read-only, you should use FormControl.setValue instead:

this.codeSelect.setValue(this.codeSelect.value.slice(1))