Issue
I was trying to make a reactive form but this error "Property 'productForm' has no initializer and is not definitely assigned in the constructor." Code for TypeScript file is -
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-create-product',
templateUrl: './create-product.component.html',
styleUrls: ['./create-product.component.css']
})
export class CreateProductComponent implements OnInit {
productForm:FormGroup;
constructor() { }
ngOnInit(){
this.productForm = new FormGroup({
name: new FormControl(null),
email: new FormControl(null),
number: new FormControl(null),
address: new FormControl(null)
});
}
onSubmit(){
console.log(this.productForm)
}
}
And HTML file for this corresponding file is-
<form [formGroup]="productForm" (ngSubmit)="onSubmit()">
<div class="mb-3">
<label class="form-label">Name</label>
<input type="name" class="form-control" formControlName="name"/>
</div>
<div class="mb-3">
<label class="form-label">Email address</label>
<input type="email" class="form-control" formControlName="email" />
</div>
<div class="mb-3">
<label class="form-label">Mobile Number</label>
<input type="number" class="form-control" formControlName="number" />
</div>
<div class="mb-3">
<label class="form-label">Address</label>
<input type="address" class="form-control" formControlName="address" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Can anyone tell me what can I do?
Solution
the rules of your linter confguration except any property to be initialized either when declaring the property or into the constructor.
You can change the rules or move the initialization to the constructor (or the declaration) :
productForm:FormGroup;
constructor() {
this.productForm = new FormGroup({
name: new FormControl(null),
email: new FormControl(null),
number: new FormControl(null),
address: new FormControl(null)
});
}
ngOnInit() {
}
Answered By - Gérôme Grignon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.