Reputation: 15
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?
Upvotes: 1
Views: 9640
Reputation: 71
You can just declare your variable this way:
productForm!:FormGroup;
Upvotes: 3
Reputation: 11
The simple approach for this problem:
Go to your angular project "tsconfig.json" file and add "strictPropertyInitialization": false
in the compilerOptions section.
` "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "forceConsistentCasingInFileNames": true, "strict": true, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "sourceMap": true, "declaration": false, "downlevelIteration": true, "experimentalDecorators": true, "moduleResolution": "node", "importHelpers": true, "target": "es2017", "module": "es2020", "lib": [ "es2020", "dom" ], "strictPropertyInitialization": false }
Upvotes: 1
Reputation: 4228
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() {
}
Upvotes: 2