0

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.

2 Answers 2

2

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];
}

Sign up to request clarification or add additional context in comments.

Comments

1

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>

1 Comment

Yes I was thinking of something like that as well, the form was very small so I didn't want overcomplication, but it may be nicer indeed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.