1

我正在尝试单击 mat-select multiple 中的按钮来实现,一个选项应该被取消选中,并且应该从选中的列表中删除。

为了删除选定的选项,我编写了如下代码:

垫选择选项:

<mat-form-field class="full-width">
          <mat-select class="multiple-location-list-search-wrapper full-width" #mulLoc required placeholder="Locations" multiple>
            <mat-option *ngFor="let l of locationsBasedOnPropertyType; let i = index" class="multiple-field-box" [hidden]="tempLocations[i]"
              [value]="l">
              {{ l.value }}
            </mat-option>
          </mat-select>
        </mat-form-field>

删除按钮:

<span (click)="deleteLocation(i, mulLoc);">Delete Location</span>
          <p>
            <strong>{{mulLoc.value[i].value}}</strong>
          </p>

删除功能:

  deleteLocation(index, multipleLocation){
    multipleLocation.selected[index]._selected = false;
    multipleLocation.selected[index]._active = false;
    multipleLocation.selected.splice(index,1);
    multipleLocation.value.splice(index,1);
  }

通过上面的实现,我可以从selected&value数组中删除选项,但它没有反映在 Material UI 中。位置选项没有被取消选中。

是否有任何黑客或内部方法可以做到这一点?

提前致谢!

4

2 回答 2

4

@Will Howel,感谢您的帮助。

但我得到了我的解决方案,如下所示:

我做了一些研究
'..app-folder../node_modules/@angular/material/select/typings/select.d.ts'
发现
writeValue(value: any): void;

我在我看来所做的改变:

<mat-select class="full-width" #mulLoc required placeholder="Locations" multiple [(ngModel)]="resLoc" name="resLoc">
    <mat-option *ngFor="let l of locations; let i = index [hidden]="tempLocations[i]" [value]="l">
{{ l.value }}
</mat-option>
</mat-select>

对象:

locations = [
{id : 'IND',value : 'india'},
{id : 'INS',value : 'indonesia'},
{id : 'THL',value : 'thailand'}
]
resLoc = [locations[0], locations[2]]

组件:这是我要求删除(取消选择)位置的功能

deleteLocation(i,mulLoc) {
    this.resLoc.splice(i,1); // my ngModel
    mulLoc.writeValue(this.resLoc); // reference variable of mat-select
  }

希望能帮助到你!快乐编码!

于 2017-11-08T07:11:47.573 回答
2

恐怕我不完全了解如何以及何时删除选项,但这里有一个似乎可以满足您需求的示例

toppings = new FormControl();

toppingList = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];

remove(topping: string) {
  // Remove from form control value
  const selectedIndex = this.toppings.value && this.toppings.value.indexOf(topping)
  if (selectedIndex > -1) {
    const newToppingsValue = this.toppings.value.slice();
    newToppingsValue.splice(selectedIndex, 1);
    this.toppings.setValue(newToppingsValue);
  }

  // Remove from topping list
  const listIndex = this.toppingList.indexOf(topping);
  if (listIndex > -1) {
    this.toppingList.splice(listIndex, 1);
  }

}

工作示例


编辑:这是一个未删除该选项,只是取消选择的示例。

于 2017-10-12T15:08:02.220 回答