I am running into some issues with trying to use FormBuilder in my Angular app and how I can set the default values in the form based on my ngModel data.
In my class, I have the following code:
form: FormGroup;
constructor(
private fb: FormBuilder,
) { }
ngOnInit() {
this.form = this.fb.group({
category: ['', [Validators.required]],
quantity: [1, [Validators.required]],
size: ['', [Validators.required]],
title: ['', [Validators.required]],
});
}
When I look at the {{ form.value | json }} in my template, it shows the original values with the empty values. So I decided to try to set the default values in the FormBuilder group like this:
this.form = this.fb.group({
category: [this.item.category, [Validators.required]],
quantity: [this.item.quantity, [Validators.required]],
size: [this.item.size, [Validators.required]],
title: [this.item.title, [Validators.required]],
});
But I am given these errors:
ERROR Error: formGroup expects a FormGroup instance.
ERROR TypeError: Cannot read properties of undefined (reading 'category')
ERROR TypeError: Cannot read properties of undefined (reading 'value')
This is my template for the form:
<form [formGroup]="form">
<ion-item lines="none">
<ion-label position="stacked">Category</ion-label>
<ion-select [(ngModel)]="item.category" [ngModelOptions]="{standalone: true}">
<ion-select-option *ngFor="let category of categories" [value]="category">
{{ category }}
</ion-select-option>
</ion-select>
</ion-item>
<ion-item lines="none">
<ion-label position="stacked">Title</ion-label>
<ion-input [(ngModel)]="item.title" [ngModelOptions]="{standalone: true}"></ion-input>
</ion-item>
<ion-item lines="none">
<ion-label position="stacked">Size</ion-label>
<ion-input [(ngModel)]="item.size" [ngModelOptions]="{standalone: true}"></ion-input>
</ion-item>
<ion-item lines="none">
<ion-label position="stacked">Quantity</ion-label>
<ion-input type="number" [(ngModel)]="item.quantity" [ngModelOptions]="{standalone: true}"></ion-input>
</ion-item>
</form>
Any thoughts what is wrong with my approach and how I can get the default values from my this.item to appear in the form?