Issue
I am doing inline editing, i get my data from server, i am trying to set my inputs value with object i got from API, but for the parent element (CatEdit) value is same for every input, and for the child (carPartSubCategories) it is empty, what am i doing wrong?
.html
<div *ngFor="let item of items">
<span>{{ item.name }}</span>
<form [formGroup]="CatEdit">
<input type="text" formControlName="name" [value]="item.name" />
</form>
<div *ngFor="let c of item.carPartSubCategories; let j = index;">
<span class="value"> {{c.name}}</span>
<form [formGroup]="subCatEdit">
<input type="text" [value]="c.name" formControlName="name" />
</form>
</div>
</div>
.ts
this.items = [
{
name: 'test name',
carPartSubCategories: [
{
name: 'test sub 1 ',
},
{
name: 'test sub 2',
},
],
},
{
name: 'test name 2',
carPartSubCategories: [
{
name: 'test sub 4',
},
{
name: 'test sub 5',
},
],
},
]
ngOnInit(): void {
this.CatEdit = this._formBuilder.group({
name: ['', Validators.required],
});
this.subCatEdit = this._formBuilder.group({
name: ['', Validators.required],
});
}
this.items.forEach(x => {
this.CatEdit.patchValue({
name: x.name
});
this.subCatEdit.patchValue({
name: x.carPartSubCategories.name
});
})
Solution
There is some confusion in your code.
On the html template you are iterating over the items
but you always use the same instance of the formGroup named CatEdit
(this is why you see the value "test name 2" set on both inputs).
What I recommend is to create a container-type FormArray
whose controls are FormGroup
that represent the single element of the items
list.
carContainer: FormArray;
....
this.carContainer = this._formBuilder.array(
this.items.map((item) => this._getFormGroup(item))
);
....
private _getFormGroup(item: Car) {
return new FormGroup({
name: new FormControl(item.name),
carPartSubCategories: new FormArray(
item.carPartSubCategories.map(
(carPart) => new FormControl(carPart.name)
)
),
});
}
On the html template you just need to do the following
<ng-container *ngFor="let group of carContainer.controls">
<form [formGroup]="group">
<input type="text" formControlName="name" />
<div
style="margin-left: 20px"
*ngFor="let control of group.get('carPartSubCategories').controls"
>
<input type="text" [formControl]="control" />
</div>
</form>
</ng-container>
I created a stackblitz for you to see the result stackblitz / reactive forms
Answered By - Luca Sacco
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.