How to stop mat-autocomplete to take custom user input values apart from given options?

后端 未结 5 1294
你的背包
你的背包 2021-02-12 20:22

I am using mat-auto complete component from material.angular.io. The default behavior is user can input any value as well as it gives options to choose from. Also you can add yo

5条回答
  •  心在旅途
    2021-02-12 20:26

    Found this solution on github it may provide a simple alternative to those who end up here.

    Create a custom validator:

    private requireMatch(control: FormControl): ValidationErrors | null {
      const selection: any = control.value;
      if (this.options && this.options.indexOf(selection) < 0) {
        return { requireMatch: true };
      }
      return null;
    }
    

    Attach it to your control (we need to bind it to this so that our validator can access our options in our component's scope)

      myControl = new FormControl(undefined, [Validators.required, this.requireMatch.bind(this)]);
    

    Optionally show error:

      Value need match available options
    

    Example here -----------> https://stackblitz.com/edit/angular-hph5yz

提交回复
热议问题