如何呈现实现接口的组件?

时间:2016-05-11 06:23:49

标签: angular angular2-template

假设我有一个接口(或实际组件)ListItemRenderer和一个实现该接口的组件MyRendererComponent(或扩展基本组件)

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

我想将此具体实现传递给另一个组件,例如

@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[];
    ...
}

显然,父组件将具有renderer类型的公共属性ListItemRenderer。问题是,我如何在<li>中使用该组件(请参阅&#34; 上面的内容?&#34;上面)?

2 个答案:

答案 0 :(得分:6)

要使用SELECT comment from aaa where movieid=2 and language='en' between6 to 10 动态添加组件,您需要https://stackoverflow.com/a/36325468/217408中解释的*ngFor之类的内容(dcl-wrapper已被弃用,而不是DynamicComponentLoader,但我没有'尝试为包装器组件引入另一个名称。)

ViewContainerRef.createComponent()

并像

一样使用它
@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();
    }    
  }
}

答案 1 :(得分:2)

GünterZöchbauer的回答非常有用,这是一个更完整的代码示例,以防其他任何人遇到此问题(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 {
}

<强>动态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;
}

<强>一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 {
}

<强>两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();
        }
    }
}

以下是生成的DOM的样子:

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

如果您需要传递参数,则必须将其传递给DclWrapperComponent,如下所示:

<强> 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
        });
    }
    ...

以下是一个示例实现:

以大写-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();
    }
}

当然,参数也应该在基础组件上声明,

<强> renderer.ts

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

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

然后,您可以在模板中传递此参数,如下所示:

<强>动态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
    ]
})
...