angular8动态组建

angular动态组建

1 指令

1.1 首先要定义一个描点来告诉Angular要把组件加载到什么地方
import { Directive, ViewContainerRef } from ‘@angular/core’;

@Directive({
selector: ‘[adHost]’,
})
export class AdDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}

2 加载组件

template: <div class="ad-banner-example"> <h3>Advertisements</h3> <ng-template adHost></ng-template> </div>
注意**adHost **就是我们的指令选择器

3 解析组件

2.1.1首先申明组件类,以及要绑定的任意数据

import { Type } from ‘@angular/core’;

export class AdItem {
constructor(public component: Type, public data: any) {}
}

2.1 .2实现组件类

你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。
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’}),
];
}
}

2.2.1 resolveComponentFactory

resolveComponentFactory 一个简单注册表,它将Components映射到生成ComponentFactory类,该类可用于创建组件的实例。用于获得给定组件类型的工厂,然后使用工厂的**creat()**方法创建该类型的组件
ComponentFactory 可用来动态创建组件的工厂基类。**resolveComponentFactory()实例化给定类型的组件的工厂。使用生成ComponentFactory.create()**方法创建该类型的组件
for (const btnItem of this.dynamicItems) {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
const viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
);
componentRef.instance.data = adItem.data;

要把这个组件添加到模板中,你可以调用 ViewContainerRef 的 createComponent()
**createComponent() **方法返回一个引用,指向这个刚刚加载的组件。 使用这个引用就可以与该组件进行交互,比如设置它的属性或调用它的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值