-1

I have a form that looks like this (please note that it is just an example):

<input type="checkbox">
<input type="text"><br>

<input type="checkbox">
<input type="text"><br>

<input type="checkbox">
<input type="text">

The ngModelGroup of all text fields is request. The ngModelGroup of all checkbox fields is important.

To achieve my goal, I could probably do something like that:

<div ngModelGroup="important">
  <input type="checkbox">
</div>  
<div ngModelGroup="request">
  <input type="text"><br>
</div>

<div ngModelGroup="important">
  <input type="checkbox">
</div>  
<div ngModelGroup="request">
  <input type="text"><br>
</div>

<div ngModelGroup="important">
  <input type="checkbox">
</div>  
<div ngModelGroup="request">
  <input type="text"><br>
</div>

Well, that's not the best solution. Is there a way doing this without opening and closing the div tag multiple times?

It would be great, if I could create both div tags only once and use attributes to assign them. Is that possible?

Reza Saadati
  • 1,224
  • 13
  • 27

1 Answers1

1

Update:

In general, you can use this method. You can add a variable in the ts file as an array of objects and loop over it.

tableData = [{
  rowClass: 'my-row-class1',
  colClass: 'my-col-class1',
  value: 'myValue1'
},
{
  rowClass: 'my-row-class2',
  colClass: 'my-col-class2',
  value: 'myValue2'
},
{
  rowClass: 'my-row-class3',
  colClass: 'my-col-class3',
  value: 'myValue3'
}];

Then in the template:

<ng-container *ngFor="let data of tableData">
    <row [ngClass]="data.rowClass">
      <col [ngClass]="data.colClass">
        {{data.value}}
      <col>
    </row>
  </ng-container>

Old Answer

You can use NgFor to loop. While it takes an array to loop over, you can use it like this:

<ng-container *ngFor="let i of [].constructor(3)">
  <div ngModelGroup="important">
    <input type="checkbox">
  </div>  
  <div ngModelGroup="request">
    <input type="text"><br>
  </div>
</ng-container>

If you need to have specific properties for each group, you can initialize an array in the ts file and use in the template in the NgFor to loop over them.

Note: Iterating using NgFor without a variable was taken from here

yazantahhan
  • 2,950
  • 1
  • 13
  • 16
  • Well, my HTML code was just an example. There are a lot of things, which could be different than the next row or the row before. I think using a loop wouldn't make sense in my case. – Reza Saadati Oct 28 '19 at 23:10