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 ...
随机推荐
- HTML5和CSS基础
1 HTML 基本语法 html标签 单标签 <img /> .<img> 双标签 <html> </html> 属性 属于标签 <img src ...
- Object C学习笔记8-字符串NSString之二
5. 字符串是否包含 hasPrefix 判断字符串是否以某个字符串开头 hasSuffix 判断字符串是否以某个字符串结尾 NSString *str1=@"Object C学习正在进行中 ...
- ASP.NET MVC - PageData的应用
一.要实现一个功能,在不同的页面放置一段如下的内容,用于采集用户行为信息: <input type='hidden' id='page_id' value='xxxx' /> <sc ...
- Linux之linux入门
学习linux之前先了解一下操作系统: 操作系统的定义: 操作系统(英语:operating system,缩写作 OS)是管理计算机硬件与软件资源的计算机程序,同时也是计算机系统的内 ...
- 安装php xdebug调试工具及性能分析工具webgrind for windows
安装php xdebug调试工具及性能分析工具webgrind for windows 第一步:查看php版本等信息 phpinfo(); 上面是 x86 NTS VC14 第二步: 下载xdebug ...
- pycharm专业版激活码
K71U8DBPNE-eyJsaWNlbnNlSWQiOiJLNzFVOERCUE5FIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZWVOYW1lIjoiI ...
- Unity3D画面渲染官方教程(一)对光照和渲染的介绍
本系列是对官方教程的翻译加上自己的一些理解译著的,官方网址:https://unity3d.com/cn/learn/tutorials/s/graphics 翻译上尽量保证准确性,但不排除省略或者添 ...
- Sqlserver 每日订单半小时数据统计
) '订单数' FROM (SELECT CASE THEN ), create_at, ) ),DATEPART(hh, create_at))+':00:00') ELSE ), create_a ...
- $.each()用法
通过它,你可以遍历对象.数组的属性值并进行处理. 使用说明 each函数根据参数的类型实现的效果不完全一致: 1.遍历对象(有附加参数) $.each(Object, function(p1, p2) ...
- linux简单命令常用随记
//查看网络信息 ifconfig //修改ip地址 ifconfig eth0 123.123.123.123 netmask 255.255.255.0 //网关设置 route add defa ...