Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Form is invalid when browser autofill

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 pristine and untouched, so the submit button is disabled.

If I click on disabled button, it enables and fires submit action, what is nice. But the default disabled aspect is pretty bad what can make some users disappointed.

Do you have some ideas about how to deal with?

like image 755
Pasp Ruby Avatar asked Nov 24 '16 19:11

Pasp Ruby


3 Answers

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" />
like image 147
Teun Avatar answered Oct 12 '22 12:10

Teun


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

like image 31
Philipp Fock Avatar answered Oct 12 '22 11:10

Philipp Fock


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

Js :

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

With JQuery :

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

Chrome 67.0.3396.99, Angular 5.1.0

like image 2
Arg0n Avatar answered Oct 12 '22 11:10

Arg0n