angular4系列之动态创建组件
来源:互联网 发布:如何测试端口通不通 编辑:程序博客网 时间:2024/05/15 00:57
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是所有通过类型进行命令式加载的组件都是入口
阅读全文
0 0
- angular4系列之动态创建组件
- Angular4动态创建组件--根据组件名称动态创建出来组件
- Angular4动态创建组件--根据组件名称动态创建出来组件
- angular4系列之国际化
- angular4系列之初识
- angular4系列之ViewEncapsulation
- angular4之父子组件之间的传值
- Angular4.0分页组件
- angular4----组件间通信
- Angular4 组件生命周期钩子
- 动态创建一个组件
- 动态创建tidhttp组件
- 动态创建vb组件
- 动态创建组件
- QtQuick动态创建组件
- Android动态创建组件
- jQuery MiniUI开发系列之:创建组件对象
- jQuery MiniUI开发系列之:创建组件对象
- 设计模式-装饰模式
- spark与storm比对与选型
- 仿京东搜索
- typeof
- 各种特殊内存填充的含义
- angular4系列之动态创建组件
- Pascal的旅行
- UVALive 7505 Hungry Game of Ants ACM/ICPC ECFinal 2015(dp+思维)
- 【计算机算法分析】递归与分治策略——二分搜索与集合划分问题
- angular表单添加查询删除
- Picasso的简单使用及封装
- 【Eclipse】安装html/jsp/xml插件
- hdoj 1180 搜索 + bfs + 优先队列
- 方格取数(1) (状态dp)