簡體   English   中英

Angular2動態引用和創建組件

[英]Angular2 dynamically reference and create Component

例如,我在一個組件中有一個選項列表,其中單擊一個組件會根據用戶的選擇動態地渲染一個組件。 這是我想象的方式:

列表組件

import { Component } from '@angular/core';
@Component({
    selector: 'list-component',
    templateUrl: `
        <ul>
            <li *ngFor="let item from list" (click)="onClick(item)">{{item.name}}</li>
        </ul>
    `
})
export class ListComponent {

    list = [
        {name: 'Component1'},
        {name: 'Component2'},
        {name: 'Component3'}
    ]

    constructor(private _listService: ListService) {

    }

    onClick(item) {
        this._listService.renderComponent(item);
    }
}

渲染組件

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

@Component({
    selector: 'render-component',
    templateUrl: `
        <div #dynamicComponent></div>
    `
})
export class RenderComponent {

    @ViewChild('dynamicComponent', { read: ViewContainerRef })
    private dynamicComponent: any;

    constructor(
        private _listService: ListService,
        private resolver: ComponentFactoryResolver
    ) {

        this._listService.onRenderComponent.subscribe(item => {
            let componentReference;

            //TODO: Get Component by reference ???

            let componentFactory = this.resolver.resolveComponentFactory(componentReference);
            this.dynamicComponent.createComponent(componentFactory);

        })
    }
}

我已經保留了有關ListService的詳細信息,但實際上它是一種允許兩個組件進行通信的服務。

我希望不要像這樣在ListComponent中引用組件:

import {Component1, Component2, Component3} from './otherComponents';

...

list = [
    {name: 'Component1', component: Component1},
    {name: 'Component2', component: Component2},
    {name: 'Component3', component: Component3}
]

...

this._listService.onRenderComponent.subscribe(item => {
    let componentReference = item.component;

    let componentFactory = this.resolver.resolveComponentFactory(componentReference);
    this.dynamicComponent.createComponent(componentFactory);

})

並讓ListService處理它。

因此,從本質上講,angular是否提供基於某些引用(例如selectorcomponentId或沿這些路線的內容)檢索Component的方法?

如果您使用的是Angular 2.0 final(我認為不是),則實際上可以通過選擇器來解析組件。

 const compFactory = this.factory.componentFactories.find(x => x.selector === 'my-component-selector');
    const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
    const cmpRef = this.vcRef.createComponent(compFactory, this.vcRef.length, injector, []);

在這里有一個動態組件創建的極簡示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM