Roberto
Roberto

Reputation: 187

Angular Material Autocomplete force selection not working

Tring to make an autocomplete with angular material that force the user to choosed from the autocomplete. i've followed this topic but its not seems to work:

Angular Material Autocomplete force selection

i tried the approach with adding a blur to the input and optionSelected. But its seems that the blur event always fire before my optionSelect so optionSeleced never get fire.

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


Upvotes: 1

Views: 5509

Answers (1)

Geggi632
Geggi632

Reputation: 564

You could subscribe to valueChanges from FormControl and check if it's valid. On blur you could check if it's valid or not and clear it. Something like this:

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("");
  }
}

Or maybe add a custom validator: https://stackoverflow.com/a/55375942

Upvotes: 1

Related Questions