5

I am trying to disable a button based on the form valid state in angular. I am using Reactive forms with Validators.required. I am using this condition [disabled]=!form.valid. It works fine if the user fills the data. But, when a browser(chrome) fills the data automatically the form state still remain same. Note: I researched on this issue and didn't find a proper solution and why this happens. Please don't duplicate this question with this question Angular Form invalid on browser autofill Is there a way to solve this.

amar
  • 443
  • 4
  • 15

1 Answers1

0

Try the code below. The idea is to check if your input has the value populated by browser and apply it using forms API (or just dispatch 'input' event). But the value is not available immediately, that's why we need setTimeout with 0 delay

@ViewChild('input', {read: ElementRef}) inputRef: ElementRef<HtmlInputElement>


ngOnInit(){
    window.setTimeout(() => this.setValueFromBrowserAutofill())
}

private setValueFromBrowserAutofill(){
    //nativeElement represents DOM element
    const browserValue = this.inputRef?.nativeElement.value; 

    //set value using forms API so Angular will know about it
    this.form.get('inputControl').setValue(browserValue)
}

update: alternative way

private setValueFromBrowserAutofill(){
    this.inputRef?.nativeElement.dispatchEvent(new Event('input'))
}
Dmitry
  • 116
  • 1
  • 5