簡體   English   中英

角材料自動完成力選擇不起作用

[英]Angular Material Autocomplete force selection not working

嘗試使用棱角材質制作自動完成內容,迫使用戶從自動完成內容中進行選擇。 我遵循了這個主題,但是它似乎不起作用:

角材料自動完成力選擇

我嘗試了向輸入和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 = '';
}


您可以從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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM