从Angular Material选择中删除项目

时间:2019-01-05 01:24:19

标签: angular 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);

1 个答案:

答案 0 :(得分:0)

FormControl.valueread-only,应改用FormControl.setValue

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