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 ...
随机推荐
- js,jsp里将数据库Date类型获取出来后格式化显示于界面
js:new Date(rowdata.updateTime).format("yyyy-MM-dd hh:mm:ss") jsp: <fmt:formatDate valu ...
- Google 日历短信通知没有了
关于 Google 日历短信通知的重要通知 从 2015 年 6 月 27 日起,Google 日历将不再发送短信通知.短信通知是我们在智能手机问世之前推出的功能.如今,智能手机和通知随处可见,即使处 ...
- 矩阵分解-----LDL分解
若一个矩阵A是正定的,那么该矩阵也可以唯一分解为\[{\bf{A = LD}}{{\bf{L}}^{\bf{T}}}\] 其中L是对角元素都为1的下三角矩阵,D是对角元素都为正数的对角矩阵.还是以三维 ...
- TPO-23 C2 Advice on choosing courses
第 1 段 1.Listen to a conversation between a student and his English professor. 请听一段学生与他的英文教授的对话. 第 2 ...
- 阿里路由框架ARouter的使用步骤
ARouter的使用步骤(以宿主APP modulebase和moduleuser 三大模块组成的工程为例) 第一步 因为路由跳转是子模块都需要用到的,所以我们在module_base模块中引入 co ...
- 文字排版 - bootStrap4常用CSS笔记
[文字常用标签] <h1>.<h2>.<h3>.<h4>.<h5>.<h6> 标题类标签,h1字体最大以次类推 <sm ...
- [操作系统]makefile
makefile文件保存了编译器和连接器的参数选项,还表述了所有源文件之间的关系(源代码文件需要的特定的包含文件,可执行文件要求包含的目标文件模块及库等). 创建程序(make程序)首先读取makef ...
- python破解网吧收费系统,远控网吧电脑设备!
我今天呢 , 我就没事跟着朋友喝酒喝酒啊.喝了很多啊.晚上到旁边的酒店开了一个房间,到了酒店才十点! 感觉没啥事情干的,那就去网吧走走看把,看到是一个嘟嘟牛的,和上次是一样的.还是照常用MS170 ...
- SmartRaiden 和 Lighting Network 进行去中心化跨链原子资产交换
作者介绍 虫洞社区·签约作者 steven bai 前言 如果能够进行以太坊和比特币跨链原子资产交换,是不是一件很酷的事情? 目前链下的扩容方式有很多,最广为人知的就是比特币的闪电网络和以太坊的雷电网 ...
- 方正 ignb路由器设置备份(自用笔记)
192.168.15.96255.255.255.0192.168.15.1219.232.46.61219.141.136.10