1

I'm trying to build a component in Angular which can render different components inside; it will be like a dynamic table, so when a user clicks on the row it expands to display something; that something depends and ideally will be anything.

So, I'm trying to use ng-content, but it does not work as I expected. I tried to reduce it to the minimum functionality that I want in a plunker.

Basically, I have a parent component (my-parent) which is a table and displays a list of rows, but for each row I also wanto to display another row below with the contents of the component projected by its parent.

my-app component

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <my-parent [data]="rows">
        <my-child *ngFor="let r of rows" [name]="r.name"></my-child>
      </my-parent>
    </div>
  `
})
export class AppComponent { 

  rows = [
    { name: 'data1' },
    { name: 'data2' },
    { name: 'data3' },
    { name: 'data4' }
  ];
}

I'm projecting 4 components here inside my-parent, one for each row.

Then in my-parent

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'my-parent',
  template: `
    <table>
      <thead>
        <tr>
          <th>my data header</th>
        </tr>
      </thead>
      <tbody>
        <ng-container *ngFor="let d of data">
          <tr>
            <td>{{ d.name }}</td>
          </tr>
          <tr>
            <td>
              <ng-content></ng-content>
            </td>
          </tr>
        </ng-container>
      </tbody>
    </table>
  `
})
export class ParentComponent {
  @Input() data: any;
}

Here I display all rows, and I want for every one to also have it's related row bellow.

And finally, my-child component

import { Component, Input } from '@angular/core';

@Component({
  selector: 'my-child',
  template: `
    <h2>name: {{ name }}</h2>
  `
})
export class ChildComponent {
  @Input() name: string;
}

This actually does something, it displays all rows in the table and then all components projected

my data header
data1
data2
data3
data4
name: data1

name: data2

name: data3

name: data4

but I want to be displayed like this

my data header
data1
name: data1

data2
name: data2

data3
name: data3

data4
name: data4

I understand the way I did it does not make much sense because I'm not telling Angular where to display each projected component, but I tried with ng-content select and it does not work because my select has to be dynamic, something like ng-content select="#{{d.name}}" and using <my-child id="{{r.name}}"></my-child>

I read about using templates and stuff, but I honestly can't make much sense of it. Anyone would care to have a look at the plunker and suggest something?

Thanks

David
  • 3,364
  • 10
  • 41
  • 84

0 Answers0