It says Cannot find name 'FormGroup' in TS file : I have done everything correctly can someone help me on this code, i have donnw what's wrong with this code . TS code
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-register-form',
templateUrl: './register-form.component.html',
styleUrls: ['./register-form.component.css']
})
export class RegisterFormComponent implements OnInit {
userForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit(): void {
this.userForm = this.formBuilder.group({
firstName: ['', [Validators.required, Validators.pattern('^[a-zA-Z] $')]],
lastName: ['',[Validators.required, Validators.pattern('^[a-zA-Z] $')]],
email: ['', [Validators.required, Validators.email]]
});
}
onSubmit(){
if(this.userForm.valid){
alert('User form is valid!!')
} else {
alert('User form is not valid!!')
}
}
}
My html code :
<form [formGroup]="userForm" (ngSubmit)="onSubmit()" >
<p >Sign up</p>
<div >
<div >
<div >
<div >
<input type="text" formControlName="firstName" id="defaultRegisterFormFirstName" placeholder="First name">
</div>
<div >
<input type="text" formControlName="lastName" id="defaultRegisterFormLastName" placeholder="Last name">
</div>
</div>
</div>
</div>
<input type="email" formControlName="email" id="defaultRegisterFormEmail" placeholder="E-mail">
<button type="submit">Sign in</button>
<hr>
</form>
found this problem in many questions in stackoverflow but no luck. Please help me for figuring out what I am doing wrong
CodePudding user response:
I don't know if this is all your code but maybe you are missig this import because I don't see it ?
import {FormControl, FormGroup} from '@angular/forms';
CodePudding user response:
You should init formbuilder after view loaded.
import {FormControl, FormGroup} from '@angular/forms';
ngAfterViewInit(){
this.userForm = this.formBuilder.group({
firstName: ['', [Validators.required, Validators.pattern('^[a-zA-Z] $')]],
lastName: ['',[Validators.required, Validators.pattern('^[a-zA-Z] $')]],
email: ['', [Validators.required, Validators.email]]
});
}