角度材料自动完成力选择不起作用

问题描述 投票:0回答:1

使用角度材料进行自动完成,强制用户从自动完成中进行选择。我已经按照这个主题,但它似乎不起作用:

Angular Material Autocomplete force selection

我尝试了为输入和optionSelected添加模糊的方法。但似乎模糊事件总是在我的optionSelect之前触发,因此optionSeleced永远不会起火。

<mat-form-field class="example-full-width">
  <div formGroupName="CityGroup">
    <input (blur)="checkCity()" #autoComplInput type="text" placeholder="city" aria-label="Number" required matInput
      formControlName="cityName" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option (click)="optionSelect(option,$event)" *ngFor="let option of filteredOptionsCity | async" [id]='0'
        [value]="option.cityName">
        {{option.cityName}}
      </mat-option>
    </mat-autocomplete>
  </div>
<mat-form-field>

TS

checkCity() {
    if (!this.selectedCity.cityName || 
    this.selectedCity.cityName !== this.form.get('CityGroup').get('cityName').value) {
        this.form.get('CityGroup').get('cityName').setValue('');
        this.selectedCity = '';
}


angular autocomplete angular-material
1个回答
1
投票

您可以从FormControl订阅valueChanges并检查它是否有效。在模糊时,您可以检查它是否有效并清除它。像这样的东西:

HTML

<form class="example-form">
    <mat-form-field class="example-full-width">
        <input (blur)="blurInput()" type="text" placeholder="Pick one"
            aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let option of options" [value]="option">
                {{option}}
            </mat-option>
        </mat-autocomplete>
    </mat-form-field>
</form>

TS

export class HomeComponent implements OnInit {
  myControl = new FormControl();
  options: string[] = ['One', 'Two', 'Three'];
  isValid = false;

  constructor() { }

  ngOnInit() {
    this.myControl.valueChanges.subscribe(val => {
      let results = this.options.filter(option => {
        return option.toLowerCase().startsWith(val.toLowerCase());
      });
      this.isValid = results.length > 0;
    });
  }

  blurInput() {
    if (!this.isValid)
      this.myControl.setValue("");
  }
}

或者可以添加自定义验证器:https://stackoverflow.com/a/55375942


推荐问答