1

I am using FormBuilder to generate form. On ngOnInit, I am calling a function which generates a login form. If any user saved their credentials, next time when they try to login these fields will be pre-filled with their saved credentials (username and password).

I want to get the status of form after rendering. I called ngAfterViewInit lifecycle hook but got INVALID status of the form even it has username and password are pre-filled.

Below is the code:

constructor(private formBuilder: FormBuilder) {}

ngOnInit() {
  this.generateForm();
}

generateForm() {
  this.loginForm = this.formBuilder.group({
    username: [null, [Validators.required]],
    password: [null, [Validators.required]],
 });    
}

ngAfterViewInit() {
  console.log(this.loginForm.status);   //INVALID
}

Didn't understand why it is showing INVALID. Is there any other lifecycle hook in which I can get the VALID status of the form if it's pre-filled?

Looking forward for the solution. Thanks in advance!

Prshant Sharma
  • 79
  • 1
  • 3
  • 10
  • Check if this works for you. https://stackoverflow.com/questions/42196896/when-input-field-is-prepopulated-the-field-is-invalid – Prashant Singh Aug 27 '22 at 18:43
  • @PrashantSingh thanks for your reply. But unfortunately, it doesn't work. – Prshant Sharma Aug 27 '22 at 18:56
  • why don't you check the validity of the form after the method that prefills the form has been called ? also, a stackblitz instance replicating your scenario would be very useful in "debugging" your issue. – CCBet Aug 27 '22 at 19:25
  • @CCBet I don't have any method that prefills the form. It's just a browser feature that lets you save the credentials after successful login. When second time you come onto login screen, your username and password are prefilled but if check the status of form, it shows me INVALID. Hope you understand the scenario now. – Prshant Sharma Aug 27 '22 at 19:34

1 Answers1

1

It's not possible to know the autofilled values until the user interacts with the page. (security feature of Chrome)

You can try this workaround and have a reference to the fields:

 @ViewChild('usernameField')
 usernameField: ElementRef;

 @ViewChild('passwordField')
 passwordField: ElementRef;

 ngAfterViewInit(): void {
     setTimeout(() => this.setValues(), 200);
 }

 setValues(): void {
this.loginForm.get('login').setValue(this.usernameField.nativeElement.value);
this.loginForm.get('password').setValue(this.passwordField.nativeElement.value);
 }
Ardit
  • 376
  • 4
  • 9