Reputation: 317
Create a form using the Angular4 ReactiveForm (version I'm using). Where do I have a form, which has Code, Year and a list of categories.
Main Form:
But I'm trying to display the form in the following way, where the category list and the products in each category would be all rows, and would all be displayed in the same table (example):
<input code>
<input year>
<table>
<tr>Category 1</tr>
<tr>Product 1.1</tr>
<tr>Product 1.2</tr>
<tr>Product 1.3</tr>
<tr>Category 2</tr>
<tr>Product 2.1</tr>
<tr>Product 2.2</tr>
</table>
<button addNewCategory />
<button addNewProduct />
I was able to display the categories as rows, but I can not display the products in each category as a row below the category row:
My typescript form:
ngOnInit() {
this.form = this._fb.group({
code: ['', Validators.required],
year: ['', Validators.required],
categories: this._fb.array([this.initCategory()])
});
}
initCategory() {
return this._fb.group({
code: ['', Validators.required],
desc: ['', Validators.required],
order: ['', Validators.required],
products: this._fb.array([this.initProduct()])
});
}
initProduct() {
return this._fb.group({
code: ['', Validators.required],
desc: ['', Validators.required],
price: ['', Validators.required]
});
}
Searching, I was told to use ngfor templates, but I can not use them, when I try to use them, the content inside the template tag is not displayed.
If I use divs, I can display the products below each category. But it does not work very well inside a table.
My template:
<div>
<form [formGroup]="form">
<input type="text" formControlName="code" />
<input type="text" formControlName="year" />
<table>
<div formArrayName="categories">
<template *ngFor="let category of form.controls['categories'].controls; let i=index">
<tr>
<td><input type="text" formControlName="code" /></td>
<td><input type="text" formControlName="desc" /></td>
<td><input type="text" formControlName="order" /></td>
</tr>
<div="products">
<template *ngFor="let product of category.controls['products'].controls; let j=index">
<tr>
<td><input type="text" formControlName="code" /></td>
<td><input type="text" formControlName="desc" /></td>
<td><input type="text" formControlName="price" /></td>
</tr>
</template>
</div>
</template>
</div>
</table>
</form>
</div>
Upvotes: 2
Views: 1011
Reputation: 24864
First of all, you should use ng-template
since template
became deprecated in v4.
Probably if you look into your browser's console, you'll see an error like this:
ERROR Error: Cannot find control with path: 'ARRAY_NAME -> FORM_CONTROL_NAME'
To fix it you must wrap the category
with formGroupName
:
<tr [formGroupName]='i'>
...
</tr>
And for products
:
<div="products" formArrayName="products">
...
<tr [formGroupName]='j'>
...
</tr>
...
</div>
It should work if it's everything correct on your component
file.
Upvotes: 2