Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 and browser autofill

I'm implementing login page with Angular reactive forms. Button "login" is disabled if form is invalid.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'signin',
    templateUrl: './signin.component.html'
})
export class SignInComponent implements OnInit {
    private signInForm: FormGroup;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.buildForm();
    }

    private buildForm(): void {
        this.signInForm = this.formBuilder.group({
            userName: ['', [Validators.required, Validators.maxLength(50)]],
            password: ['', [Validators.required, Validators.maxLength(50)]]
        });

        this.signInForm.valueChanges
            .subscribe((data: any) => this.onValueChanged(data));

        this.onValueChanged();
    }

    private onValueChanged(data?: any) {
        console.log(data);
    }

So, when I launch it in browser, I have prepopulated fields "userName" and "passwords". And in console I have values '{ userName: "[email protected]", password: "" }' and as a result button "login" is disabled. But if I click somewhere on page it trigger onValueChanged and I see '{ userName: "[email protected]", password: "123456" }', and button "login" is enabled.

If I go in incognito mode. I have no prepopulated fields (they are empty), but when I populate (select) values, then in console I see '{ userName: "[email protected]", password: "123456" }', and button "login" is enabled without any extra click.

May be they are different events? Autofill and autocomplete? And angular works with them differently?

What is the best way to resolve it? And why onValueChanged function is executed only once when browser autofill fields?

like image 931
A. Gladkiy Avatar asked Jan 30 '17 09:01

A. Gladkiy


2 Answers

The problem in Chrome browser: it does not allow access to the value of the password field after autofill (before user click on the page). So, there are two ways:

  1. remove validation of the password field;
  2. disable password autocompletion.
like image 173
Yaroslav Sivakov Avatar answered Nov 07 '22 23:11

Yaroslav Sivakov


I found out that you can use autocomplete="new-password"

As is decribed here

This way your password fields will not be autofilled at all, and that was my case. There are many others autocomplete attributes available in the link above.

like image 11
rochasdv Avatar answered Nov 07 '22 22:11

rochasdv