[Fixed] Angular template-driven form in array best practice

Issue

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.

Solution

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

Leave a Reply

(*) Required, Your email will not be published