Dynamically create templates in Angular and retrieve them using ViewChildren

I want to create some dynamic components inside another component, but not once, many times. And this number is also dynamic.

So, I used ComponentFactoryResolver to create a component and then ViewChild to add that component dynamically. The problem, as I said, is that I need to do this in many places, so I will have to use ViewChildren to fetch all references and inject the component (with specific inputs).

I have a plunker where I have reduced the problem to what I need. I have a component that is passed an array of data and the type of component to create.

@Component({
  selector: 'my-app',
  template: `
    <div>
      <my-parent [data]="rows" [inner]="component">
      </my-parent>
    </div>
  `
})
export class AppComponent { 

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

  component = ChildComponent;
}

      

In my parent, I am displaying a table with one row for each item in the data received as a parameter, but also, I want to display below each row, another row with a type component also passed as a parameter.

As an example, above all the lines I am doing this exact thing for one component where I pass name = 'TOTAL'. So I use <ng-container #entry>

to get link and input component.

I am trying to do the same for dynamic links and it doesn't work. I created a directive host to get it using a ViewChildren with a specific id, but then when I try to create the component dynamically it doesn't work.

This is the code

@Directive({
  selector: 'host'
})
export class Host {
  @Input() id: string;
}

@Component({
  selector: 'my-parent',
  template: `
    <table>
      <thead>
        <tr>
          <th>my data header</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            <ng-container #entry></ng-container>
          </td>
        </tr>
        <ng-container *ngFor="let d of data; let i = index;">
          <tr>
            <td>{{ d.name }}</td>
          </tr>
          <tr>
            <td>
              <host id="{{i}}"></host>
            </td>
          </tr>
        </ng-container>
      </tbody>
    </table>
  `
})
export class ParentComponent implements OnInit, AfterContentInit {

  @Input() data: any;
  @Input() inner: any;

  @ViewChildren(Host) hosts: QueryList<Host>;
  @ViewChild('entry', { read: ViewContainerRef }) entry: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {}

  ngOnInit() {
  }

  ngAfterViewInit() {
    if (this.hosts) {
      const componentFactory = this.resolver.resolveComponentFactory(this.inner);
      this.hosts.forEach(host => {
        console.log(host);
        const component = host.createComponent(componentFactory);
        component.instance.name = host.id;
      });
    }
  }

  ngAfterContentInit() {
    const componentFactory = this.resolver.resolveComponentFactory(this.inner);
    const component = this.entry.createComponent(componentFactory);
    component.instance.name = 'TOTAL';
  }

}

      

And here is the plunker

It seems that the host items I am getting cannot be injected. Any ideas to fix this?

Thank.

+3


source to share


1 answer


Injecting a ViewContainerRef into a host directive

@Directive({
  selector: 'host'
})
export class Host {
  constructor(private viewRef: ViewContainerRef) {}

  @Input() id: string;
}

      

then run host.viewRef.createComponent (componentFactory)



 ngAfterViewInit() {
  if (this.hosts) {
   const componentFactory = this.resolver.resolveComponentFactory(this.inner);
    this.hosts.forEach(host => {
     console.log(host);
     const component = host.viewRef.createComponent(componentFactory);
     component.instance.name = host.id;
  });
}

      

}

+1


source







All Articles