[Angular 2] Generate Angular 2 Components Programmatically with entryComponents & ViewContainerRef

本文介绍如何使用 Angular 2 的 ViewContainer 和 ComponentFactoryResolver 动态创建组件,并解释了 entryComponents 在模块元数据中的作用,确保动态加载的组件不会被编译器优化掉。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You can generate Angular 2 components using a combination of ViewContainer and ComponentFactory, but you must always remember to add the components you want to generate to your list of entryComponents otherwise the compiler will optimize the component class out of your project.

 

ViewChild:

For example, in HomComponent, we created a div with ref "#container", if you log out the element we can see:

import {Component, ViewChild} from '@angular/core';
import {SimpleService} from "../../serivces/simple.service";

@Component({
    moduleId: module.id,
    selector: 'home',
    template: '<div #container></div>'
})
export class HomeComponent {

    @ViewChild('container') container;

    constructor(private simpleService: SimpleService) {
    }

    ngAfterContentInit(){

    }

}

It is a native Element. 

 

Actually you can View the child in other different way:

    @ViewChild('container', {
        read: ViewContainerRef
    }) container;

"ViewContainerRef": Represents a container where one or more Views can be attached.

 

For example we now want to create component Programmatically:

import {Component, ViewChild, ViewContainerRef, ComponentFactoryResolver} from '@angular/core';
import {WidgetThree} from "../widgets/widget-three.component";

@Component({
    moduleId: module.id,
    selector: 'home',
    template: '<div #container></div>'
})
export class HomeComponent {

    @ViewChild('container', {
        read: ViewContainerRef
    }) container;

    constructor(private resolver: ComponentFactoryResolver) {
    }

    ngAfterContentInit(){

        const WidgetFactory = this.resolver.resolveComponentFactory(WidgetThree);
        this.container.createComponent(
            WidgetFactory
        )
    }

}

See https://angular.io/docs/ts/latest/api/core/index/ViewContainerRef-class.html

But now, it won't work:

It says it cannot find WidgetThree, even we already define in Module:

import { NgModule} from '@angular/core';
import { CommonModule } from '@angular/common';
import {WidgetOneComponent} from './widget-one.component';
import {WidgetTwoComponent} from './widget-two.component';
import {WidgetThree} from './widget-three.component';

@NgModule({
    imports: [CommonModule],
    declarations: [WidgetOneComponent, WidgetTwoComponent, WidgetThree],
    exports: [WidgetOneComponent, WidgetTwoComponent, WidgetThree, CommonModule]
})
export class WidgetsModule {

}

 

The problem for that is because Angualr2 optimize the imports component, check whether it is used in template, if not, then remove the component from the bundle file. Because in HomeComponent tempalte, we didn't use WidgetThree compoennt, so it was removed.

 

To solve the problem, we can use "entryComponents":

import { NgModule} from '@angular/core';
import { CommonModule } from '@angular/common';
import {WidgetOneComponent} from './widget-one.component';
import {WidgetTwoComponent} from './widget-two.component';
import {WidgetThree} from './widget-three.component';

@NgModule({
    imports: [CommonModule],
    declarations: [WidgetOneComponent, WidgetTwoComponent, WidgetThree],
    entryComponents: [WidgetThree],
    exports: [WidgetOneComponent, WidgetTwoComponent, WidgetThree, CommonModule]
})
export class WidgetsModule {

}

 

"entryComponents" just tell angular, no matter what, keep the componet into the bundle, don't remove it.

And now, we can actually create multi WidgetThree component programmatically:

export class HomeComponent {

    @ViewChild('container', {
        read: ViewContainerRef
    }) container;

    constructor(private resolver: ComponentFactoryResolver, private simpleService: SimpleService) {
    }

    ngAfterContentInit(){
        const WidgetFactory = this.resolver.resolveComponentFactory(WidgetThree);
        this.container.createComponent(WidgetFactory);
        this.container.createComponent(WidgetFactory);
        this.container.createComponent(WidgetFactory);
        this.container.createComponent(WidgetFactory);
        this.container.createComponent(WidgetFactory);
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值