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

后端 未结 5 1281
你的背包
你的背包 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:24

    You can do something like this

    Markup:

    
    
    
    
    
        {{ option.name }}
    
    
    

    Component:

    selectedOption;
    changeMyControl(): void {
        if (isUndefined(this.selectedOption) {
            // also check selected item and entered text are not same
            this.myForm.get('myControl').setErrors({'incorrect': true});
        }
    }
    
    onSelectedOption(isSelected: boolean, id: number): void {
        if (isSelected) {
            setTimeout(() => {
                const option = this.options.filter(bt => bt.id === id);
                if (option.length > 0) {
                    this.selectedOption= option[0];
                   // patch formcontrol value here
                }
            }, 200);
        }
    }
    

提交回复
热议问题