Angular 2 - Form is invalid when browser autofill

前端 未结 7 1908
广开言路
广开言路 2021-01-31 16:48

I have a Login Form which has email and password fields.

I\'ve chosen for browser autofill.

The problems is: When browser autofills login form, both fields are p

相关标签:
7条回答
  • 2021-01-31 17:16

    I solved this problem with the ChangeDetectorRef Provider.
    Simply do a manual detectChanges() before you check if the input is valid.

    If you aren't able to check after a button click, then hear on the Input-Event of the Input-Element with the event-binding (input)=changedetectorfunc() and call the changeDetector in this function.
    Therefore it must work.
    Hope, it helps you.

    useful links:

    • https://angular.io/api/core/ChangeDetectorRef
    • Angular 2 change event on every keypress

    Best wishes

    0 讨论(0)
  • 2021-01-31 17:20

    I seem to have solved this by just simulating a click on the page AfterViewInit.

    public ngAfterViewInit(): void {
        $('body').click();
    }
    

    Chrome 67.0.3396.99, Angular 5.1.0

    0 讨论(0)
  • 2021-01-31 17:23

    According to the offical docs

    "pristine" means the user hasn't changed the value since it was displayed in this form
    

    So if you have a validation in your form it's a better approach to check if the form is "valid" or "invalid"

    <button [disabled]="formName.invalid">Submit</button>
    

    So it doesn't matter if the form is pristine or not.

    0 讨论(0)
  • 2021-01-31 17:28

    I had the same problem.

    I solved it by: - removing the Validators.required validator for the password field in the component - using the <input ... required ...> directive at the tag in the template

    0 讨论(0)
  • 2021-01-31 17:32

    I solved it by also checking if the form was touched when displaying error messages. So, for example, the submit button looks like this

    <input type="submit" class="btn btn-default" [disabled]="loginFormGroup.invalid && loginFormGroup.touched" />
    
    0 讨论(0)
  • 2021-01-31 17:32

    this is not the best practice for code but it will work for sure-

    if you are having two way binding then its very easy task just check for length of both textbox if it is greater then zero then return false else return true and call the method in disabled attribute. Method-

        validcheck() {
             return username.length <= 0 || password.length <= 0;     
        }
    

    and call the method inside button disabled attribute

        <button [disabled]="validcheck()">Submit</button>
    
    0 讨论(0)
提交回复
热议问题