Angular 动态组件
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 动态组件的更多相关文章
- Angular动态组件
一.主页面: app.component.html: <button (click)="load();">动态</button> 2<div #dom ...
- angular 动态组件类型
出处:https://github.com/Penggggg/angular-component-practices 组件类型1:纯函数功能,而没有视图部分,即Factory(类似于$http) pr ...
- Angular 学习笔记 (动态组件 & Material Overlay & Dialog 分析)
更新: 2019-11-24 dialog vs router link refer : https://stackoverflow.com/questions/51821766/angular-m ...
- Angular动态创建组件之Portals
这篇文章主要介绍使用Angular api 和 CDK Portals两种方式实现动态创建组件,另外还会讲一些跟它相关的知识点,如:Angular多级依赖注入.ViewContainerRef,Por ...
- angular2 学习笔记 ( Dynamic Component 动态组件)
更新 2018-02-07 详细讲一下 TemplateRef 和 ViewContainerRef 的插入 refer : https://segmentfault.com/a/1190000008 ...
- vuejs动态组件给子组件传递数据
vuejs动态组件给子组件传递数据 通过子组件定义时候的props可以支持父组件给子组件传递数据,这些定义的props在子组件的标签中使用绑定属性即可,但是如果使用的是<component> ...
- C++ 类的动态组件化技术
序言: N年前,我们曾在软件开发上出现了这样的困惑,用VC开发COM组件过于复杂,用VB开发COM组件发现效率低,而且不能实现面向对象的很多特性,例如,继承,多态等.更况且如何快速封装利用历史遗留的大 ...
- Hibernate学习---第五节:普通组件和动态组件
一.普通组件映射配置 1.创建组件类,代码如下: package learn.hibernate.bean; /** * 组件类 */ public class Phones { private St ...
- vue2入坑随记(二) -- 自定义动态组件
学习了Vue全家桶和一些UI基本够用了,但是用元素的方式使用组件还是不够灵活,比如我们需要通过js代码直接调用组件,而不是每次在页面上通过属性去控制组件的表现.下面讲一下如何定义动态组件. Vue.e ...
随机推荐
- 【Java源码解析】ThreadLocal
简介 线程本地变量,用于同一线程之间的传递.每一个线程对象都保存在两个ThreadLocalMap,threadLocals和inheritableThreadLocals,后者会继承父线程的本地变量 ...
- Spring是什么?优点是什么?
大部分项目都少不了Spring的身影,为什么大家对他如此青睐,而且对他的追捧丝毫没有减退之势呢 Spring是什么: Spring是一个轻量级的DI和AOP容器框架. 说它轻量级有一大部分原因是相对与 ...
- 转载-30分钟搞定后台登录界面(103个后台PSD源文件、素材网站)
原文:30分钟搞定后台登录界面(103个后台PSD源文件.素材网站) 目录 一.界面预览 二.PSD源文件预览 三.工具分享 四.资源说明 五.素材下载网站 六.下载 去年八月时要做一个OA系统为 ...
- css选择器分类与作用
本文旨在总结css中各种选择器及其相应用途(持续更新) 通配符(全局)选择器 样式:*{} 示例: 总结:选定文档中所有类型的对象,如图所示写在css样式文件开头用来定义全局通用的一些属性.font- ...
- SSH结合EasyUI系统(一)———简单介绍
鉴于前文<不仅仅是吐槽>,决定将自己学过的和在学的东西整理一下放进园子:做一个好园友! 接下来将会持续更新的是近一段时间在学的java web中比较流行的框架SSH(Struts+Spri ...
- SQL Server Management Studio 键盘快捷键
光标移动键盘快捷键 操作 SQL Server 2012 SQL Server 2008 R2 左移光标 向左键 向左键 右移光标 向右键 向右键 上移光标 向上键 向上键 下移光标 向下键 向下键 ...
- CSS基础范例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 学习python,第四篇:Python 3中bytes/string的区别
原文:http://eli.thegreenplace.net/2012/01/30/the-bytesstr-dichotomy-in-python-3 python 3中最重要的新特性可能就是将文 ...
- Discuz3.3精仿小米风格整站模板制作——1、新建模板方案
术语说明: 模板——模板是一堆按照规定命名方式的html文件,用于指定整个论坛不同页面的外观. 标签——标签和模板共同作用以实现论坛换肤功能,其中标签主要控制页面显示什么数据,显示多少条等. 风格—— ...
- spring-boot+swagger实现WebApi文档
1.引用依赖包 <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-s ...