3

Let's say I got an interface (or an actual component) ListItemRenderer and a component MyRendererComponent that implements that interface (or extends the base component)

@Component({
    selector: 'my-renderer',
    template: '<div>My renderer</div>'
})
export class MyRendererComponent implements ListItemRenderer {
    ...
}

I'd like to pass this concrete implementation to another component, e.g.

@Component({
    selector: 'my-list',
    template: `
        <ul [renderer]="renderer" [items]="items">
            <li *ngFor="let item of items">
                <!-- what goes here? -->
            </li>
        </ul>
    `
})
export class MyList {
    @Input() renderer: ListItemRenderer;
    @Input() items: any[];
    ...
}

Obviously, the parent component would have a public property rendererof type ListItemRenderer. The question is, how do I go about using that component in my <li> (see "what goes here?" above)?

Thorsten Westheider
  • 10,572
  • 14
  • 55
  • 97

2 Answers2

6

To add components dynamically using *ngFor you need something like the dcl-wrapper explained in https://stackoverflow.com/a/36325468/217408 (DynamicComponentLoader is deprecated in favor of ViewContainerRef.createComponent() but I didn't try to introduce another name for the wrapper component.)

@Component({
  selector: '[dcl-wrapper]', // changed selector in order to be used with `<li>`
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private resolver: ComponentResolver) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
   this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
      this.cmpRef = this.target.createComponent(factory)
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

and use it like

@Component({
    selector: 'my-list',
    template: `
        <ul  [items]="items">
            <li *ngFor="let item of items" dcl-wrapper [type]="renderer" ></li>
        </ul>
    `
})
export class MyList {
    @Input() renderer: ListItemRenderer;
    @Input() items: any[];
    ...
}
Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I get `Error: No Directive annotation found on [object Object]` using this approach. If I change the decorator from `@Component` to `@Directive` (which would make sense to me, as `DclWrapper` is used as a directive rather than a component) the template definition becomes invalid, if I get rid of the template, there is no `target` reference. – Thorsten Westheider May 11 '16 at 07:36
  • Just because it uses an attribute selector doesn't make it a directive. It's a directive if it doesn't have a view. I haven't tried if it works as directive. It might work if `ViewContainerRef` is a constructor parameter (to get it injected) instead of acquiring it using `@ViewChild()`. I guess the problem is that you pass a component instance instead of the type. My mistake I didn't spot that `renderer` is `ListItemRenderer` instead of `Type`. Either you pass a type or you move the `resolver.resolveComponent()` to the user of the dcl-wrapper to already pass a resolved component to `renderer`. – Günter Zöchbauer May 11 '16 at 07:44
  • I don't know what type `resolveComponent()` returns. Anyway, you can't create a component with `new MyComponent()`. This only creates a class instance but not a component. – Günter Zöchbauer May 11 '16 at 07:44
  • Gonna investigate in more detail once I get a chance. – Thorsten Westheider May 14 '16 at 06:39
  • This is a working solution, the details of which I'm going to post as a separate answer for reference. I'm only missing one thing now and that is passing a parameter to the dynamic component, I'll make that a new question. – Thorsten Westheider May 14 '16 at 21:04
  • 1
    You can use a shared service or `this.cmpRef.instance.someProp = someValue;` in `updateComponent` after `this.cmpRef = this.target.createComponent(factory);` (not tested just from memory - time for bed, can looks it up tomorrow if it doesn't work) – Günter Zöchbauer May 14 '16 at 21:06
  • @Günter Zöchbauer your solution works great. but I have an interesting issue when i try to remove an Item from the array with array.splice(index,1) it always removes the last one. – Joe B Nov 04 '16 at 15:56
  • Hard to tell. I'd suggest you create a new question with a Plunker that demonstrates the issue. I guess it's a problem with the index value you pass. Did you verify that `index` has the expected value? – Günter Zöchbauer Nov 04 '16 at 16:23
  • @Günter Zöchbauer I asked this as a new question please follow http://stackoverflow.com/questions/40681694/removing-dynamic-component-warped-in-dcl-wapper-angular2 , Thanks – Joe B Nov 18 '16 at 16:21
2

The answer from Günter Zöchbauer is spot-on, here's a more complete code sample in case anybody else should encounter this problem (Angular2 RC1).

app.component.ts

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

import { DynamicListComponent } from './dynamic-list.component';
import { TwoRendererComponent } from './two-renderer.component';
import { Renderer } from './renderer';

@Component({
    selector: 'app',
    template: `
        <h2>Dynamic List</h2>
        <dynamic-list [items]="items" [renderer]="renderer"></dynamic-list>
    `,
    directives: [
        DynamicListComponent
    ]
})
export class AppComponent {
    items: string[] = [ 'one', 'two', 'three' ];
    renderer: Renderer;
    constructor() {
        this.renderer = TwoRendererComponent;
    }
}

renderer.ts

export class Renderer {
}

dynamic-list.component.ts

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

import { Renderer } from './renderer';
import { DclWrapperComponent } from './dcl-wrapper.component';

@Component({
    selector: 'dynamic-list',
    template: `
        <ul>
            <li *ngFor="let item of items" dcl-wrapper [type]="renderer">
            </li>
        </ul>
    `,
    directives: [
        DclWrapperComponent
    ]
})
export class DynamicListComponent {
    @Input() items: string[] = [];
    @Input() renderer: any;
}

one-renderer.component.ts

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

import { Renderer } from './renderer';

@Component({
    selector: 'one-renderer',
    template: '<div>ONE</div>'
})
export class OneRendererComponent implements Renderer {
}

two-renderer.component.ts

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

import { Renderer } from './renderer';

@Component({
    selector: 'two-renderer',
    template: '<div>TWO</div>'
})
export class TwoRendererComponent implements Renderer {
}

dcl-wrapper.component.ts

import {
    Component,
    ViewChild,
    ViewContainerRef,
    ComponentRef,
    ComponentResolver,
    ComponentFactory,
    Input
} from '@angular/core';

import { Renderer } from './renderer';

@Component({
    selector: '[dcl-wrapper]',
    template: `<div #target></div>`
})
export class DclWrapperComponent {
    @ViewChild('target', { read: ViewContainerRef }) target;
    @Input() type: any;
    @Input() input: string;
    cmpRef: ComponentRef<Renderer>;
    private isViewInitialized: boolean = false;

    constructor(private resolver: ComponentResolver) { }

    updateComponent() {
        if (!this.isViewInitialized) {
            return;
        }
        if (this.cmpRef) {
            this.cmpRef.destroy();
        }
        this.resolver.resolveComponent(this.type).then((factory: ComponentFactory<any>) => {
            this.cmpRef = this.target.createComponent(factory)
        });
    }
    ngOnChanges() {
        this.updateComponent();
    }
    ngAfterViewInit() {
        this.isViewInitialized = true;
        this.updateComponent();
    }
    ngOnDestroy() {
        if (this.cmpRef) {
            this.cmpRef.destroy();
        }
    }
}

Here's what the resulting DOM looks like:

<app>
    <h2>Dynamic List</h2>
    <dynamic-list>
        <ul>
            <!--template bindings={}-->
            <li dcl-wrapper="">
                <div></div>
                <two-renderer _ngcontent-gce-4="">
                    <div>TWO</div>
                </two-renderer>
            </li>
            ...
        </ul>
    </dynamic-list>
</app>

If you need to pass a parameter, you'll have to pass it to DclWrapperComponent like so:

dcl-wrapper.component.ts

export class DclWrapperComponent {
    @ViewChild('target', { read: ViewContainerRef }) target;
    @Input() type: any;
    @Input() input: string;  // <-- the parameter
    cmpRef: ComponentRef<Renderer>;
    private isViewInitialized: boolean = false;

    constructor(private resolver: ComponentResolver) { }

    updateComponent() {
        if (!this.isViewInitialized) {
            return;
        }
        if (this.cmpRef) {
            this.cmpRef.destroy();
        }
        this.resolver.resolveComponent(this.type).then((factory: ComponentFactory<any>) => {
            this.cmpRef = this.target.createComponent(factory);
            this.cmpRef.instance.input = this.input;  // <-- pass value to the newly created component
        });
    }
    ...

Here's an example implementation:

to-uppercase-renderer.component.ts

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

import { Renderer } from './renderer';

@Component({
    selector: 'to-uppercase-renderer',
    template: '<div>{{output}}</div>'
})
export class ToUppercaseRendererComponent implements Renderer, OnInit {
    @Input() input: string;
    output: string;
    ngOnInit() {
        this.output = this.input.toUpperCase();
    }
}

Of course, the parameter should be declared on the base component as well,

renderer.ts

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

export abstract class Renderer {
    @Input() input: string;
}

You can then pass this parameter in your template as follows:

dynamic-list.component.ts

...
@Component({
    selector: 'dynamic-list',
    template: `
        <ul>
            <li *ngFor="let item of items" dcl-wrapper [type]="renderer" [input]="item">
            </li>
        </ul>
    `,
    directives: [
        DclWrapperComponent
    ]
})
...
Thorsten Westheider
  • 10,572
  • 14
  • 55
  • 97