angular知识点--动态组件

动态组件

碎碎念:都是一些自己在学习过程中的一点体会,如果有什么不对的感谢大家指正一起学习!


实现动态加载组件,最重要的3个部分:viewchild,viewContainerRef , componentFactoryResolver

  1. ViewChild:一个属性装饰器,用来从模板视图中获取对应的元素,可以通过模板变量获取,获取时可以通过 read 属性设置查询的条件,就是说可以把此视图转为不同的实例
  2. ViewContainerRef :一个视图容器,可以在此上面创建、插入、删除组件等等
  3. ComponentFactoryResolve:一个服务,动态加载组件的核心,这个服务可以将一个组件实例呈现到另一个组件视图上

第一步:在组件所在模块的declarations和entryComponents中声明组件:

//module.ts

import { TestThreeComponent } from './test-three/test-three.component';
import { TestTwoComponent } from './test-two/test-two.component';
import { TestOneComponent } from './test-one/test-one.component';

const declare = [
  TestOneComponent,
  TestTwoComponent,
  TestThreeComponent
]

@NgModule({
  declarations: [
    ...declare
  ],
  entryComponents: [...declare]
})

第二步:定义动态组件所需的内容

//html
<!-- 组件切换链接按钮 -->
<a (click)="load('one')" class="list">one</a>
<a (click)="load('two')" class="list">two</a>
<a (click)="load('three')" class="list">three</a>

<!-- 动态组件容器 -->
<div #dynamic></div>
//ts

export class AppComponent implements OnInit, AfterViewInit {

 // 定义动态组件对象
  cmpData = {
    'one': TestOneComponent,
    'two': TestTwoComponent,
    'three': TestThreeComponent
  }

// 定义动态组件容器
  @ViewChild('dynamic', { read: ViewContainerRef })
  dmRoom: ViewContainerRef;

  constructor(
    private cfr: ComponentFactoryResolver
  ) {}

  // 定义动态切换组件方法
  loadComponent(comName):void {
    const com = this.cfr.resolveComponentFactory(comName);
    this.dmRoom.clear();  // 清空视图
    this.dmRoom.createComponent(com);
  }
  
   // 定义点击事件方法
  load(name: string) {
    this.loadComponent(this.cmpData[name]);
  }

  ngAfterViewInit(): void {
   // 默认加载的动态组件
    this.loadComponent(this.cmpData['one'])

  }

}

实现效果:
在这里插入图片描述
//默认加载得是“one”(test-one组件)内容。然后根据选择加载不同的组件


声明:
本文完全参考下面文章,感谢作者,非常有条理,排版也舒服,学习了学习了。原文章

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值