Repeat two elements directly in ngFor Angular

Viewed 290

Angular 9

I simply need to repeat two HTML elements using *ngFor.

if I write the following code

<dl>
  <div *ngFor="let item of columns">
    <dt>{{ item.name }}</dt>
    <dd>{{ item.field }}</dd>
  </div>
</dl>

then I am receiving 3 HTML warnings

Element 'div' cannot be nested inside element 'dl'
Element 'dt' cannot be nested inside element 'div'
Element 'dd' cannot be nested inside element 'div'

if I wrote the following code

<dl>
  <ng-template [ngFor]="let item of columns">
    <dt>{{ item.name }}</dt>
    <dd>{{ item.field }}</dd>
  </ng-template>
</dl>

I will receive an angular error in the runtime

ERROR Error: Uncaught (in promise): Error: Template parse errors: Parser Error: Unexpected token let at column 1 in [let item of columns]

and if I wrote the following code

<dl *ngFor="let item of columns">
  <dt>{{ item.name }}</dt>
  <dd>{{ item.field }}</dd>
</dl>

then the dl element will be repeated and this is something that I do not want at all.

can someone give me a solution for that?

2 Answers

Try this:

<dl>
 <ng-container *ngFor="let item of columns">
  <dt>{{ item.name }}</dt>
  <dd>{{ item.field }}</dd>
 </ng-container>
</dl>

ng-container

Doesn't <ng-container> work in this case?

The Angular ng-container is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

<dl>
    <ng-container *ngFor="let item of columns">
        <dt>{{ item.name }}</dt>
        <dd>{{ item.field }}</dd>
    </ng-container>
</dl>
Related