angular4系列之动态创建组件

11 篇文章 0 订阅
6 篇文章 0 订阅

Angular如何在组件中动态加载组件

参考博客1 参考博客2 参考博客3

找到宿主页面

  • 在Angular中,我们通常需要一个宿主(Host)来给动态加载的组件提供一个容器。这个宿主在Angular中就是<ng-template>
    ### 创建为组件提供容器的指令
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
    selector: '[dl-host]'
})
export class DlHostDirective {
    constructor(public viewContainerRef: ViewContainerRef) { }
}
  • 这里注入了一个ViewContainerRef的服务,它的作用就是为组件提供容器,并且提供了一系列的管理这些组件的方法。
  • 可以在宿主ts模块文件中通过@ViewChild获取到dl-host的实例,因此进而获取到其中的ViewContainerRef
@ViewChild(DlHostDirective) dlHost: DlHostDirective;

宿主文件的ts文件中

  • 引入指令
  • 引入需要动态创建的组件
  • 创建组件的工厂,引入ComponentFactoryResolver服务
  • 具体代码如下
import { Component, ViewChild, ComponentFactoryResolver } from '@angular/core';
import { DlHostDirective } from './dl-host.directive';
import { AComponent } from './a/a.component';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'app works!';
    @ViewChild(DlHostDirective) dlHost: DlHostDirective;
    constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

    ngAfterViewInit() {
        this.dlHost.viewContainerRef.createComponent(
            this.componentFactoryResolver.resolveComponentFactory(AComponent)
        );
    }
}

在.module.ts中将需要生成的组件注册为一个@NgModule.entryComponent

@NgModule({
    entryComponents: [AComponent]
})
  • entryComponents是所有通过类型进行命令式加载的组件都是入口
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值