I am new to Angular, I use version 11. And I have a problem with the formGroup attribute in my html file.
Error :
'FormGroup | null' is not assignable to type 'FormGroup'. Type 'null' is not assignable to type 'FormGroup'.
2 <form [formGroup]="produitFormGroup">
My html code.
<form [formGroup]="produitFormGroup">
<div class="form-group">
<label>Nom</label>
<input type="text" class="form-control" formControlName="name">
</div>
<div class="form-group">
<label>Prix</label>
<input type="text" class="form-control" formControlName="price">
</div>
<div class="form-group">
<label>Quantite</label>
<input type="text" class="form-control" formControlName="quantity">
</div>
<div class="form-group">
<label>Selected</label>
<input type="checkbox" formControlName="selected">
</div>
<div class="form-group">
<label>Available</label>
<input type="checkbox" formControlName="available">
</div>
<button class="btn btn-success">Enregistrer</button>
</form>
And my ts file code:
produitFormGroup: FormGroup | null= null;
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.produitFormGroup = this.fb.group({
name:["", Validators.required],
price:[0, Validators.required],
quantity:[0, Validators.required],
selected:[true, Validators.required],
available:[true, Validators.required]
});
}
You need to add ! operator after produitFormGroup like this:
produitFormGroup!: FormGroup;
It is a way to tell the compiler explicitly that an expression has value other than null or undefined
Actually at produitFormGroup: FormGroup | null= null; Statement you are trying to assign null value to the FormGroup explicitly but the problem is TypeScript's type checker doesn't allow these kind of assignment.
produitFormGroup: FormGroup | null= null; to produitFormGroup: FormGroup;."strict": true, to "strict": false, on tsconfig.jsonchange produitFormGroup: FormGroup | null= null; to produitFormGroup!: FormGroup;.
Here, The non-null assertion operator(!) will take care of null and undefined values
Checkout this link to find some other ways to fix or know about this issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With