首页 > 解决方案 > 从 Angular Material 中删除项目选择

问题描述

我正在使用 Angular 7.2 创建一个选择控件,如下所示:

        <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>

这按预期工作。我有一些代码可以删除选定的项目,如下所示:

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

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

尽管这确实将其从所选项目的数组中删除。如果我从选择控件中选择新值,则仍会选择所有原始项目(即勾选)。

如何清除所选项目?

在@Maarti 的回复之后,我的代码现在可以使用

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

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

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

标签: angularangular-material

解决方案


FormControl.value只读的,你应该FormControl.setValue改用:

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

推荐阅读