Angular 动态组件

实现步骤

  • Directive
  • HostComponent
  • 动态组件
  • AdService
  • 配置AppModule
  • 需要了解的概念

Directive

  • 我们需要一个Directive来标记动态组件是在哪个容器组件内部进行渲染的。
  • 这个Directive可以获取对容器组件的引用。
  • 仅此而已。
import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
selector: '[appAd]',
})
export class AdDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}

HostComponent

  • 我们需要一个容器组件,所有动态组件都是在这个容器组件中创建,销毁,重新创建。。。
  • 需要将动态组件需要展示的数据和动态组件进行绑定。
import { Component, Input, AfterViewInit, ViewChild, ComponentFactoryResolver, OnDestroy } from '@angular/core';

import { AdDirective } from './ad.directive';
import { AdItem } from './ad-item';
import { AdComponent } from './ad.component'; @Component({
selector: 'app-add-banner',
template: `
<div class="ad-banner">
<h3>Advertisements</h3>
<!-- hostElement 在此! -->
<ng-template appAd></ng-template>
</div>
`
})
export class AdBannerComponent implements AfterViewInit, OnDestroy {
@Input() ads: AdItem[];
currentAddIndex: number = -1;
@ViewChild(AdDirective) adHost: AdDirective;
subscription: any;
interval: any; constructor(private componentFactoryResolver: ComponentFactoryResolver) { } // 在 view 初始化结束后才开始创建动态组件
ngAfterViewInit() {
this.loadComponent();
this.getAds();
} ngOnDestroy() {
clearInterval(this.interval);
} loadComponent() {
this.currentAddIndex = (this.currentAddIndex + 1) % this.ads.length;
let adItem = this.ads[this.currentAddIndex]; // 这里使用了工厂模式。其实Angular对于模板中出现的每一个Component都会创建一个ComponentFactory。在创建销毁时
// 实际上使用的是组件工厂来创建组件的新实例。
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component); let viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();
// 传入对应的组件工厂来创建新的组件,并保存新组建的引用。
let componentRef = viewContainerRef.createComponent(componentFactory);
// 绑定数据
(<AdComponent>componentRef.instance).data = adItem.data;
} getAds() {
this.interval = setInterval(() => {
this.loadComponent();
}, 3000);
}
}
// add-item.ts
import { Type } from '@angular/core'; export class AdItem {
constructor(public component: Type<any>, public data: any) {}
}
// ad.component.ts
export interface AdComponent {
data: any;
}

在AppComponent 中使用

// app.component.ts

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

import { AdService }         from './ad.service';
import { AdItem } from './ad-item'; @Component({
selector: 'app-root',
template: `
<div>
<app-add-banner [ads]="ads"></app-add-banner>
</div>
`
})
export class AppComponent implements OnInit {
ads: AdItem[]; constructor(private adService: AdService) {} ngOnInit() {
this.ads = this.adService.getAds();
}
}

创建动态组件

// hero-job-ad.component.ts
import { Component, Input } from '@angular/core'; import { AdComponent } from './ad.component'; @Component({
template: `
<div class="job-ad">
<h4>{{data.headline}}</h4>
{{data.body}}
</div>
`
})
export class HeroJobAdComponent implements AdComponent {
@Input() data: any; }
// hero-profile.component.ts
import { Component, Input } from '@angular/core'; import { AdComponent } from './ad.component'; @Component({
template: `
<div class="hero-profile">
<h3>Featured Hero Profile</h3>
<h4>{{data.name}}</h4>
<p>{{data.bio}}</p> <strong>Hire this hero today!</strong>
</div>
`
})
export class HeroProfileComponent implements AdComponent {
@Input() data: any;
}

创建service

import { Injectable }           from '@angular/core';

import { HeroJobAdComponent }   from './hero-job-ad.component';
import { HeroProfileComponent } from './hero-profile.component';
import { AdItem } from './ad-item'; @Injectable()
export class AdService {
getAds() {
return [
new AdItem(HeroProfileComponent, {name: 'Bombasto', bio: 'Brave as they come'}), new AdItem(HeroProfileComponent, {name: 'Dr IQ', bio: 'Smart as they come'}), new AdItem(HeroJobAdComponent, {headline: 'Hiring for several positions',
body: 'Submit your resume today!'}), new AdItem(HeroJobAdComponent, {headline: 'Openings in all departments',
body: 'Apply today'}),
];
}
}

配置 AppModule

// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HeroJobAdComponent } from './hero-job-ad.component';
import { AdBannerComponent } from './ad-banner.component';
import { HeroProfileComponent } from './hero-profile.component';
import { AdDirective } from './ad.directive';
import { AdService } from './ad.service'; @NgModule({
imports: [ BrowserModule ],
providers: [AdService],
declarations: [ AppComponent,
AdBannerComponent,
HeroJobAdComponent,
HeroProfileComponent,
AdDirective ],
// 注意这里,需要手动引入动态组件的class,放入 entryComponents数组中,这样
// Angular才能为动态组件创建组件工厂。如果不写,Angular在模板中不会发现这两个组件的具体引用,
// 可能在打包时将组件代码排除。
entryComponents: [ HeroJobAdComponent, HeroProfileComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {
constructor() {}
}
ng serve

完成。

需要了解的概念

  • ViewContainerRef
  • ViewChild
  • ComponentFactoryResolver
  • ComponentFactory
  • ComponentRef

Angular 动态组件的更多相关文章

  1. Angular动态组件

    一.主页面: app.component.html: <button (click)="load();">动态</button> 2<div #dom ...

  2. angular 动态组件类型

    出处:https://github.com/Penggggg/angular-component-practices 组件类型1:纯函数功能,而没有视图部分,即Factory(类似于$http) pr ...

  3. Angular 学习笔记 (动态组件 & Material Overlay & Dialog 分析)

    更新: 2019-11-24  dialog vs router link refer : https://stackoverflow.com/questions/51821766/angular-m ...

  4. Angular动态创建组件之Portals

    这篇文章主要介绍使用Angular api 和 CDK Portals两种方式实现动态创建组件,另外还会讲一些跟它相关的知识点,如:Angular多级依赖注入.ViewContainerRef,Por ...

  5. angular2 学习笔记 ( Dynamic Component 动态组件)

    更新 2018-02-07 详细讲一下 TemplateRef 和 ViewContainerRef 的插入 refer : https://segmentfault.com/a/1190000008 ...

  6. vuejs动态组件给子组件传递数据

    vuejs动态组件给子组件传递数据 通过子组件定义时候的props可以支持父组件给子组件传递数据,这些定义的props在子组件的标签中使用绑定属性即可,但是如果使用的是<component> ...

  7. C++ 类的动态组件化技术

    序言: N年前,我们曾在软件开发上出现了这样的困惑,用VC开发COM组件过于复杂,用VB开发COM组件发现效率低,而且不能实现面向对象的很多特性,例如,继承,多态等.更况且如何快速封装利用历史遗留的大 ...

  8. Hibernate学习---第五节:普通组件和动态组件

    一.普通组件映射配置 1.创建组件类,代码如下: package learn.hibernate.bean; /** * 组件类 */ public class Phones { private St ...

  9. vue2入坑随记(二) -- 自定义动态组件

    学习了Vue全家桶和一些UI基本够用了,但是用元素的方式使用组件还是不够灵活,比如我们需要通过js代码直接调用组件,而不是每次在页面上通过属性去控制组件的表现.下面讲一下如何定义动态组件. Vue.e ...

随机推荐

  1. 开发中常遇到的linux系统配置操作整理

    一直以来,工作中使用xshell连接linux虚拟机.常常需要在虚拟机中搭建一个新的Linux系统,为了满足操作需要,必不可少的是一系列配置.之前对这些指令都是记录在云笔记,但是零零散散,每次用时,都 ...

  2. 闭包初体验 -《JavaScript面向对象编程指南》

    下面是我对闭包的理解:(把他们整理出来,整理的过程也是在梳理) 参考<JavaScript面向对象编程指南> 1.首先,在理解闭包之前: 我们首先应该清楚下作用域和作用域链 作用域:每个函 ...

  3. spring boot 使用及最佳实践

    第一部分,spring boot 文档 Spring boot的使用 使用maven进行构建 用户可以通过继承spring-boot-starter-parent来获取默认的依赖. l  默认java ...

  4. DICOM 协议学习笔记之 What is DICOM

    什么是DICOM? Dicom (Digital Imaging and Communications in Medicine)即医学数字成像和通信,是医学图像和相关信息的国际标准(ISO 12052 ...

  5. Netty源码分析第3章(客户端接入流程)---->第3节: NioSocketChannel的创建

    Netty源码分析第三章: 客户端接入流程 第三节: NioSocketChannel的创建 回到上一小节的read()方法: public void read() { //必须是NioEventLo ...

  6. linux-shell-screen后台调用-后台运行脚本和命令-仿start命令-伪窗口界面

    序 我比较熟练bat.cmd脚本.刚接触使用shell时,总会习惯想用windows窗口界面来套用shell脚本.于是找到screen后台命令,它可以交互shell脚本,保持后台运行.但是在批处理ba ...

  7. WinDbg使用学习

    拿到软件崩溃之后产生的crash文件,后缀名为dump 使用winDbg的File-----> Open Crash Dump 打开Crash文件 File---------> Symbo ...

  8. Linux系列——安装双系统Ubuntu

    作为一个穷人,电脑破得不行却没钱换,怎么办呢,不如换个Ubuntu吧,没有Windows那么多后台应用,在我这台古董上稍微流畅一点. Linux有很多发行版,比较流行和适合入门的就是Ubuntu和De ...

  9. 如何使用g++编译调用dll的c++代码

    本文将有以下4个部分来讲如何使用g++编译调用dll的c++代码. 1.如何调用dll 2.动态链接和静态链接的区别 3.g++的编译参数以及如何编译调用dll的c++代码 4.总结 1.如何调用dl ...

  10. Scrum Meeting 11.05

    成员 今日任务 明日计划 用时 徐越 代码移植 学习ListView+simpleAdapter,actionBar.阅读并修改前端代码 4h 赵庶宏 服务器配置,代码移植  构建后端数据库,进行完善 ...