首页 > 解决方案 > 根据条件更改 mat-autocomplete 选项的值,并过滤这些选项

问题描述

我正在尝试让用户在输入中输入至少 3 个字符后出现 mat-options。当输入的长度小于 3 时,选项数组将为空。如果输入的长度大于 2,那么我可以在数组中赋值。

另外,我希望在用户写入输入时过滤结果。

我已经设法过滤了结果(使用材料文档),并且如果输入的长度大于 2,我还设法更改了选项的值。但我不能让两者都有相同的时间。

这是我的组件的代码:

export class FormComponent implements OnInit {
  myForm!: FormGroup;
  options: string[] = null;
  filteredOptions: Observable<string[]>;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.myForm = this.fb.group({ myControl: ['', [Validators.required]] });
    this.filteredOptions = this.filterOption(this.myControl, this.options);
  }

  updateOptions() {
    let controlLength: number = this.myControl.value.length;
    if (controlLength === 3) this.options = ['Stack', 'Overflow', 'isAwesome'];
    else if (controlLength < 3) this.options = [''];
  }

  filterOption(control: AbstractControl, controlOptions: string[]) {
    return control.valueChanges.pipe(
      startWith(''),
      map((controlValue) => this._filter(controlValue, controlOptions))
    );
  }

  private _filter(controlValue: string, controlOptions: string[]): string[] {
    return controlOptions?.filter((option) =>
      option.toLowerCase().includes(controlValue.toLowerCase())
    );
  }

  get myControl() {
    return this.myForm.get('myControl');
  }

  displayFn(subject) {
    return subject ? subject.name : undefined;
  }

这是我的组件的 html:

  <mat-form-field>
        <mat-label>My Input <span class="required">*</span></mat-label>
        <input
            matInput 
            type="text" 
            formControlName="myControl" 
            [matAutocomplete]="auto"
            (input)="updateOptions()"
        />
        <mat-autocomplete #auto >
            <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
                {{ option }}
            </mat-option>
        </mat-autocomplete>
    </mat-form-field>

先感谢您!

标签: angularfilterangular-materialautocompleteconditional-statements

解决方案


推荐阅读