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]
});
}
null
type declaration and the problem should go away.produitFormGroup: FormGroup | null= null;
would becomeproduitFormGroup: FormGroup;
, so you understand why the formGroup directive only takes an argument of type FormGroup, you have declared yours as type FormGroup "or" null, which is why you are seeing that error. – Italic