N
N
Nazariy Lazarchuk2020-11-24 14:26:14
JavaScript
Nazariy Lazarchuk, 2020-11-24 14:26:14

How does ng-content work in *ngFor loop?

I am making a game in Angular to learn this framework.
Game 2048. There is a field, and on it are cells with the numbers 2, 4, 8, ...;

Field component:

<ng-container *ngFor="let row of matrix, let i = index">
      <ng-container *ngFor="let col of matrix[i], let j = index">
        <div class="col-box">
          <ng-content></ng-content>
          {{ i + ':' + j }}
        </div>
      </ng-container>
    </ng-container>


I leave ng-content in order to pass the cell inside from the outside.

But when I pass something, only the last one in the cycle is displayed (see code and screenshot), and all cells must be filled.
<app-field>
    <h1>Work</h1>
</app-field>

5fbcecae0adc2214472740.png

What am I doing wrong? And how should component composition work in this case?

The same code, only in Svelte.js (in which everything works as intended):
<!-- компонент Field-->
{#each new Array(squares) as row, i}
    {#each new Array(squares) as col, j}
      <div class="col-box" style={getColStyles(i, j)}>
        <slot {i} {j} />
      </div>
    {/each}
  {/each}

  <!-- компонент Game -->
  <Field let:i let:j>
    <Col {i} {j} />
  </Field>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2020-11-24
@LazarchukNazar

That's how it works, everything is correct. Rearranges each time to a new place, as a result, the content is where the last ng-content is.
For reproduction it is necessary to interpose through a template or the structural directive. For example like this https://stackblitz.com/edit/angular-ivy-qav868?fil...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question