Been trying to access form instance values bt they are all null..It worked fine in tempalate driven forms. I have imported ReactiveFormsModule. I have played around with the attr but I cant find what am missing?? The form is invalid the moment I use Validators.required meaning its empty
.component.html
<form [formGroup] ="tryForm" (ngSubmit)="onSubmit()" >
<div >
<label>Name</label><br>
<input type="text" FormControlName ="name">
<span *ngIf="tryForm.invalid">Name required</span>
</div>
<!-- <div *ngIf="name.invalid" ></div> -->
<div >
<label>Email</label><br>
<input type="text" FormControlName ="email">
</div>
<div >
<label>Message</label><br>
<input type="text" FormControlName ="message">
</div>
<button type = "submit" >Submit</button>
</form>
.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl,FormGroup,Validators} from '@angular/forms';
import { Router} from '@angular/router'
@Component({
selector: 'app-log-in',
templateUrl: './log-in.component.html',
styleUrls: ['./log-in.component.css']
})
export class LogInComponent implements OnInit {
tryForm = this.fb.group({
name : [''],
email: [''],
message: [''],
});
constructor(private fb:FormBuilder,
private router: Router) { }
onSubmit(){
if (this.tryForm.status == "VALID"){
alert("Form Submitted Successfully.")
alert(this.tryForm.get("name")?.value);
this.tryForm.reset();
CodePudding user response:
first you need to change the html FormControlName to formControlName. you can read the full explanation here.
HTML
<form [formGroup]="tryForm" (ngSubmit)="onSubmit(tryForm.value)">
<div >
<label>Name</label><br />
<input type="text" formControlName="name" />
<span *ngIf="tryForm.invalid">Name required</span>
</div>
<div >
<label>Email</label><br />
<input type="text" formControlName="email" />
</div>
<div >
<label>Message</label><br />
<input type="text" formControlName="message" />
</div>
<button type="submit">Submit</button>
</form>
after that change your ts like bellow, make sure you initialize the form on ngOnInit.
TS
export class LogInComponent implements OnInit {
tryForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.createForm();
}
createForm() {
this.tryForm = this.fb.group({
name : [''],
email : [''],
message: [''],
});
}
onSubmit(data) {
console.log(data);
}
}
I replicate your code here
CodePudding user response:
change this <input type="text" FormControlName ="email"> to this;
<input type="text" formControlName="email">
and build your form on ngOnInit,
ngOnInit(){
this.tryForm = this.fb.group({
name : [''],
email: [''],
message: [''],
});
}
