清除垫选择选择角材料

时间:2020-11-05 07:22:30

标签: html angular typescript angular-material angular8

我已经实现了mat-multi-select选项。我具有搜索功能,可以一次选择多个选项。单击“生成”按钮后发布选择,我想清除所有选择。我可以清除搜索栏中的值,但是如果我打开多选下拉菜单,则仍会选择值。如何清除这些值。

HTML代码

<mat-select [formControl]="cMultiCtrl" [multiple]="true" required (selectionChange)="selectionChange($event)">
              <mat-option>
              <ngx-mat-select-search placeholderLabel="Search" noEntriesFoundLabel="No Matching Value Found" [formControl]="cMultiFilterCtrl"></ngx-mat-select-search>
            </mat-option>
              <mat-option *ngFor="let val of filteredCMulti | async" [value]="val.value">
                {{val.name}}
              </mat-option>
            </mat-select>

// the button on click of which I want to clear everything post API call

<button mat-raised-button (click)="generate()" class="download-button">Generate
  </button>

TS代码

 public filteredCMulti: ReplaySubject<any[]> = new ReplaySubject<any[]>(1);
 public cMultiCtrl: FormControl = new FormControl();

ngOnInit() {
this.filteredCMulti.next(this.cvalues.slice());
this.cMultiFilterCtrl.valueChanges
      .pipe(takeUntil(this._onDestroy))
      .subscribe(() => {
        this.filterBanksMulti();
      });
}
ngAfterViewInit() {
    this.setInitialValue();
  }
ngOnDestroy() {
  this._onDestroy.next();
  this._onDestroy.complete();
}
private setInitialValue() {
  this.filteredCMulti
    .pipe(take(1), takeUntil(this._onDestroy))
    .subscribe(() => {          
      this.singleSelect.compareWith = (a, b) => a.id === b.id;
    });
}
 selectionChange(event){
      this.cvalue = event.value;
  }
private filterBanksMulti() {
  if (!this.cvalues) {
    return;
  }
  let search = this.cMultiFilterCtrl.value;
  if (!search) {
    this.filteredCMulti.next(this.cvalues.slice());
    return;
  } else {
    search = search.toLowerCase();
  }
  // filter the banks
  this.filteredCMulti.next(
    this.cvalues.filter(bank => bank.name.toLowerCase().indexOf(search) > -1)
  );
}
generate(){
    let msg = '';
     
// some logic here

        else{
          this.commonService.showSnackBar("Value generated")
          this.filteredCMulti = new ReplaySubject; // this clears the search bar but not values, they are still selected 
          this.table();
        }}
    })
  }


1 个答案:

答案 0 :(得分:0)

为您的<mat-select>提供一个元素引用

<mat-select #matRef [formControl]="cMultiCtrl" [multiple]="true" required (selectionChange)="selectionChange($event)">
          <mat-option>
          <ngx-mat-select-search placeholderLabel="Search" noEntriesFoundLabel="No Matching Value Found" [formControl]="cMultiFilterCtrl"></ngx-mat-select-search>
        </mat-option>
          <mat-option *ngFor="let val of filteredCMulti | async" [value]="val.value">
            {{val.name}}
          </mat-option>
        </mat-select>

并更新您的ts文件,例如:

@ViewChild('matRef') matRef: MatSelect;

clear() {
  this.matRef.options.forEach((data: MatOption) => data.deselect());
}

您可以通过有条件地调用clear()

来优化deselect()