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

[Angular 2] Generate Angular 2 Components Programmatically with entryComponents & ViewContainerRef的更多相关文章

  1. Angular 2 to Angular 4 with Angular Material UI Components

    Download Source - 955.2 KB Content Part 1: Angular2 Setup in Visual Studio 2017, Basic CRUD applicat ...

  2. Angular 1与 Angular 2之间的一些差别

    现在在用ng1.5.8做一个项目,ng的优点和特性我就不用多说了,ng1在陆续更新到1.5/1.6后就没再推出新版本了,ng2已经面世测试很久了,如同很多系统和框架一样,每个大的版本更新都会有新特性加 ...

  3. 使用Angular CLI生成 Angular 5项目

    如果您正在使用angular, 但是没有好好利用angular cli的话, 那么可以看看本文. Angular CLI 官网: https://github.com/angular/angular- ...

  4. AngularJs angular.injector、angular.module

    angular.injector 创建一个injector对象, 调用injector对象的方法可用于获取服务以及依赖注入. 格式:angular.injector(modules); modules ...

  5. angular.js 的angular.copy 、 angular.extend 、 angular.merge

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  6. Angular - - angular.injector、angular.module

    angular.injector 创建一个injector对象, 调用injector对象的方法可用于获取服务以及依赖注入. 格式:angular.injector(modules); modules ...

  7. Angular 学习笔记 (Angular 9 & ivy)

    refer : https://blog.angularindepth.com/all-you-need-to-know-about-ivy-the-new-angular-engine-9cde47 ...

  8. Angular JS - 5 - Angular JS 模块和控制器

    1.引入 1.5版本的angularjs,直接打印angular对象: --> <!DOCTYPE html> <html> <head lang="en ...

  9. 【Angular】关于angular引用第三方组件库无法改变其组件样式 :host ::ng-deep

    [Angular]关于angular引用第三方组件库无法改变其组件样式 :host ::ng-deep css修改:无效 .ant-input-affix-wrapper .ant-input:not ...

随机推荐

  1. 一个Web页面的生命周期 ,面试常常被问到

    常规页生命周期阶段 一般来说,页要经历下表概述的各个阶段.除了页生命周期阶段以外,在请求前后还存在应用程序阶段,但是这些阶段并不特定于页.有关更多信息,请参见 ASP.NET 应用程序生命周期概述. ...

  2. android学习笔记---发送状态栏通知

    发送消息的代码如下: //获取通知管理器 NotificationManager mNotificationManager = (NotificationManager) getSystemServi ...

  3. Node-APN 开源推送服务

    Node-APN是一个开放的结合了苹果推送通知的Node.js模块,该源码模块使用简单,反馈服务支持.错误处理,在发送出错时自动重发.遵从苹果的最佳实践. Node-APN(github)

  4. Time vs Story Points Estimation [转]

    One of the most common questions we get is whether to estimate in time or points. It seems like poin ...

  5. VS2010 删除空行

    查找内容:^:b*$\n 替换为: 查找范围:当前文档 使用:正则表达式 vs2013 ^\s*(?=\r?$)\n

  6. 第二百三十五天 how can I 坚持

    其实昨天听遗憾的,尽头看了新闻,有好多人都出去赏雪了,可惜了,最遗憾的是没有叫上你一块去. 晚上喝了点酒,抽了两根烟,以前基本不喝酒,就别提抽烟了,陈小春的<算你狠>,该如何是好. 经常在 ...

  7. 指令式Callback,函数式Promise:对node.js的一声叹息

    原文:Callbacks are imperative, promises are functional: Node's biggest missed opportunity promises 天生就 ...

  8. HDu 1001 Sum Problem 分类: ACM 2015-06-19 23:38 12人阅读 评论(0) 收藏

    Sum Problem Time Limit: 1000/500 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total ...

  9. Java反射机制(创建Class对象的三种方式)

    1:了解什么是反射机制? 在通常情况下,如果有一个类,可以通过类创建对象:但是反射就是要求通过一个对象找到一个类的名称:   2:在反射操作中,握住一个核心概念: 一切操作都将使用Object完成,类 ...

  10. XML的特殊字符处理

    XML中共有5个特殊的字符,分别是:&<>“’.如果配置文件中的注入值包括这些特殊字符,就需要进行特别处理.有两种解决方法:其一,采用本例中的<![CDATA[ ]]> ...