角材料MatSelect:如何显示选项列表中未包含的选项?

时间:2019-08-09 13:55:06

标签: angular angular-material angular-forms

通过反应形式进行以下设置:

<mat-form-field>
    <mat-select [formControl]="selectFormCtrl">
        <!-- Option search field -->
        <ngx-mat-select-search *ngIf="canFilter" [formControl]="optionsFilter"></ngx-mat-select-search>
        <mat-option *ngFor="let option of filteredOptions | async | slice:0:MAX_ITEMS" [value]="option.value">
            {{ option.text }}
        </mat-option>
        <mat-option *ngIf="showNothingFound()" [value]="" disabled>Nothing found</mat-option>
    </mat-select>
</mat-form-field>

问题:我想在slice:0:MAX_ITEMS处截断列表。例如。用户可能宁愿在搜索字段中键入诸如国家/地区列表之类的长列表,以过滤选项。但是,如果有一个选项集未出现在列表本身中,则组件将不会显示该选项。

想法:确保所选的选项始终包含在filteredOptions中。

是否有一种更优雅/更简单的解决方案来实际在MatSelect中设置选定的选项,以便在任何情况下都可以显示值?

1 个答案:

答案 0 :(得分:1)

您可以创建一个可观察的过滤后的切片选项:

filteredOptionsSliced$ = combineLatest(
  this.filteredOptions, 
  this.selectFormControl.valueChanges.pipe(startWith(null))
).pipe(map((filteredOptions, selectedOption) => {
  const slicedOptions = filteredOptions.slice(0, MAX_ITEMS);
  if (selectedOption && !slicedOptions.find(slicedOption => slicedOption.value === selectedOption.value)) {
    slicedOptions.push(selectedOption);
  }
  return slicedOptions;
}))

并在没有切片管道的模板中使用它:

 <mat-option *ngFor="let option of filteredOptionsSliced$ | async" [value]="option.value">
相关问题