Angular Material Autocomplete force selection

后端 未结 6 1466
情书的邮戳
情书的邮戳 2021-02-07 09:18

In my angular 5 application I have some matAutocomplete, but I want to force the selection of oone of suggestions, so I am following this approach: stackblitz but for some reas

6条回答
  •  长发绾君心
    2021-02-07 10:18

    You can Create custom Validator , this will validate it perfectly tested code:

    stateCtrl = new FormControl(null,[forbiddenNamesValidator(this.states)])
    
    
    export function forbiddenNamesValidator(States: any[]): ValidatorFn {
      return (control: AbstractControl): { [key: string]: any } | null => {
        const index = States.findIndex(State=> {
          return (new RegExp('\^' + State.name + '\$')).test(control.value);
        });
        return index < 0 ? { 'forbiddenNames': { value: control.value } } : null;
      };
    }
    

提交回复
热议问题