How can I render a component that implements an in

2019-01-25 22:11发布

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)?

2条回答
对你真心纯属浪费
2楼-- · 2019-01-25 22:27

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[];
    ...
}
查看更多
乱世女痞
3楼-- · 2019-01-25 22:44

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
    ]
})
...
查看更多
登录 后发表回答