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

时间:2019-04-28 12:19:31

标签: angular autocomplete angular-material

尝试使用棱角材质制作自动填充内容,迫使用户从自动填充内容中进行选择。 我已经遵循了这个主题,但是它似乎没有用:

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 = '';
}


1 个答案:

答案 0 :(得分: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

相关问题