I tried to fix this problem with an $any(), but I don't think I did it correctly. Could someone help me with this error, please?
The error occurs on these lines of code:
get email(): AbstractControl { return this.loginForm.get('email')}
get password(): AbstractControl { returnthis.loginForm.get('password')}
Code provided below:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
@Component({
selector: 'bwm-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm!: FormGroup;
emailPattern = /^(([^<>()\[\]\\.,;:\s@"] (\.[^<>()\[\]\\.,;:\s@"] )*)|(". "))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$/
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.initForm();
}
initForm() {
this.loginForm = this.fb.group({
email: ['', [Validators.required, Validators.pattern(this.emailPattern)]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}
login() {
if (this.loginForm.invalid) { return; }
alert(this.diagnostic);
}
get email(): AbstractControl { return this.loginForm.get('email')}
get password(): AbstractControl { return this.loginForm.get('password')}
get diagnostic(): string {
return JSON.stringify(this.loginForm.value);
}
}
<section id="login">
<div >
<div >
<div >
<h1>Login</h1>
<!-- <div *ngIf="notifyMessage" >
Some message
</div> -->
<form [formGroup]="loginForm">
<div >
<label for="email">Email</label>
<input
formControlName="email"
type="email"
id="email">
<div
*ngIf="email.invalid && !email.pristine"
>
<div *ngIf="email.errors?.['required']">
Email is required.
</div>
<div *ngIf="email.errors?.['pattern']">
Must be valid email format!
</div>
</div>
</div>
<div >
<label for="password">Password</label>
<input
formControlName="password"
type="password"
id="password">
<div
*ngIf="password.invalid && !password.pristine"
>
<div *ngIf="password.errors?.['required']">
Password is required.
</div>
<div *ngIf="password.errors?.['minlength']">
Minimum length of password is 6 characters.
</div>
</div>
</div>
<button
(click)="login()"
[disabled]="loginForm.invalid"
type="submit"
>Submit</button>
</form>
<!-- <div *ngIf="errors.length > 0" >
<p *ngFor="let error of errors">
{{error.detail}}
</p>
</div> -->
</div>
<div >
<div >
<h2 >Hundreds of awesome places in reach of few clicks.</h2>
<img src="assets/images/login-image.jpg" alt="">
</div>
</div>
</div>
</div>
</section>
CodePudding user response:
get email(): AbstractControl {
return this.loginForm.get('email');
}
this.loginForm.get('email');
returns AbstractControl<ɵGetProperty<TRawValue, P>> | null
, so it can be AbstractControl
or null
. See here.
The problem is that you defined get email()
as AbstractControl
and not as AbstractControl | null
.