Reputation: 6306
I need multiple forms in a table that is generated dynamically using a template-driven form, it works well the way that I did it, but I'm not sure it's correct.
<div *ngFor="let row of rows">
<form #f="ngForm" (submit)="submit(f)">
...
</form>
</div>
the #f
will be defined many times and I'm wondering if that could cause an issue? I could eventually give a dynamic naming (if that's possible?), but as it works this way I don't want to overcomplicate it.
Upvotes: 0
Views: 753
Reputation: 122
It won't be an issue since each form tag will have a different context. Creating template reference variables dynamically is not possible.
If you don't like having template reference variables, you can have the index of the current form and query it using ViewChildren.
template:
<div *ngFor="let row of rows; let i=index">
<form (submit)="submit(i)">
...
</form>
</div>
Component:
@ViewChildren('div > form') forms: Array<NgForm>;
submit(index: number){
var currentForm:NgForm = forms[index];
}
Upvotes: 2
Reputation: 93
You can create a custom form component and add it in the declarations array of the module, inside the custom-form-component.html
of the component, create the input form controls and have the form submit to a method in the custom-form-component.ts
.
You can pass the value of rows as an @Input() rowData
value to the form-component. This will enable you to have a fine-grained control over the form's behaviour.
Don't forget to implement OnChange
strategy for performance reasons.
So your parent page's html might look something like this:
<div *ngFor="let row of rows">
<custom-form [rowData]="row">
</custom-form>
</div>
Upvotes: 1