Angular How to prevent manual entry in dropdown?

Viewed 552

How to prevent manual entry in angular dropdown?

For example my search dropdown value is like RAM, RAJ, KIRI, GURU..... and so on and it has the id value of 1, 2, 3, 4..... and so on

my problem is if I type in input value for search. It must be not to accept the manual type search entry value if I click submit. How to do that? help me to solve it

<mat-form-field>
  <input placeholder="Select type" matInput formControlName="e_id"
    [matAutocomplete]="cotype">
      <mat-autocomplete #cotype="matAutocomplete" [displayWith]="displayFn">
        <mat-option *ngIf="isLoading" class="is-loading">Loading...</mat-option>
         <ng-container *ngIf="!isLoading">
          <mat-option *ngFor="let e of ceList" [value]="e.id">{{e.name}}</mat-option>
        </ng-container>
      </mat-autocomplete>
    </mat-form-field> 
2 Answers

One simple approach is to pass object as value to mat-option

<mat-option *ngFor="let e of ceList" [value]="e">{{e.name}}</mat-option>

then in your submit function simply check:


public onSubmit(){
  if(typeof  this.form.value.e_id === 'object') {
  //it's an object, manual entry will be string 

  } else {
   alert('Choose option from the list, manual entry not allowed!);

  }
}

In your displayFn, you can then process the value from object i.e

displayFn(e_id){
 return e_id.id;
}

Second Approach
You can also create a custom validator and then pass it to your input, that way your form will not be valid unless value is selected:

 private ceListSelectionValidator(fc: FormControl) {
    if (typeof fc.value === 'string') {
      return { incorrectValue: `Selected value '${fc.value}' is not from list` }
    }
    return null;
  }

Pass this validator to your input during form creation:

 this.form = this.formBuilder.group({ 
      e_id: ['', this.ceListSelectionValidator]
    });

and in your html, display the error to user:

<span *ngIf="form.control.e_id.errors?.incorrectValue">
    {{form.control.e_id.errors?.incorrectValue}}
</span>
Related