Home > front end >  How to render multiple Component-type variables through a template
How to render multiple Component-type variables through a template

Time:10-27

I'm trying to make a simple grid/table of Components, where each cell is a specific instance of another "tile" Component. The parent grid component's TS file looks like this:

import { Component, OnInit } from '@angular/core';
import { TileComponent } from '../tile/tile.component';

function defaultMap() {
  //just makes a 2d array of default TileComponents
  let map: TileComponent[][] = [];
  for (var i = 0; i < 19; i  ) {
    map[i] = [];
    for (var j = 0; j < 19; j  ) {
      map[i][j] = new TileComponent();
    }
  }
  return map;
}

@Component({
  selector: 'app-world-viewer',
  templateUrl: './world-viewer.component.html',
  styleUrls: ['./world-viewer.component.scss']
})
export class WorldViewerComponent implements OnInit {

  tiles: TileComponent[][] = defaultMap();

  constructor() { }

  ngOnInit(): void {
  }

}

And its template file looks like this:

<table>
    <tbody>
        <tr *ngFor="let row of tiles">
            <td *ngFor="let tile of row">
                <!-- how do I render tile? -->>
            </td>
        </tr>
    </tbody>
</table>

The TileComponent currently has totally default .html and .ts files.

I've trawled through a lot angular docs (and posts here) and I've found solutions to similar problems, but am unsure of how it works in this case.

CodePudding user response:

In your template reference the component you want to render such as:

<td *ngFor="let tile of row">
    <app-yourcomponent></app-yourcomponent>
</td>

If you want to have a reference to your specific component to do DOM manipulation with it, assign a custom id based on the index returned by your ngFor. For example.

// yourcomponent.ts
<td *ngFor="let tile of row; let i = index">
    <app-yourcomponent [customID]="'myCustomerId-'   i"></app-yourcomponent>
</td>

Than in your yourcomponent.ts file get back the ID with @Input() customID: string; and assign it yo your yourcomponent.html dom such as:

// yourcomponent.html
<div  id="{{customID}}">
</div>

That should work!

  • Related