Angular使用动态加载组件方法实现Dialog的示例


Posted in Javascript onMay 11, 2018

网上的文章和教程基本上写到组件加载完成就没了!没了?!而且都是只能存在一个dialog,想要打开另一个dialog必须先销毁当前打开的dialog,之后看过 material 的实现方式,怪自己太蠢看不懂源码,就只能用自己的方式来实现一个dialog组件了

Dialog组件的目标:可以同时存在多个Dialog,可销毁指定Dialog,销毁后html中无组件残留且提供回调

动态加载组件的实现方式有两种,angular4.0版本之前使用ComponentFactoryResolver来实现,4.0之后可以使用更便捷的ngComponentOutlet来实现,

通过ComponentFactoryResolver实现动态载入

首先理一下ViewChild、ViewChildren、ElementRef、ViewContainerRef、ViewRef、ComponentRef、ComponentFactoryResolver之间的关系:

ViewChild 与 ViewChildren

ViewChild是通过模板引用变量(#)或者指令(directive)用来获取 Angular Dom 抽象类,ViewChild可以使用 ElementRef 或者 ViewContainerRef 进行封装。

@ViewChild('customerRef') customerRef:ElementRef;

ViewChildren通过模板引用变量或者指令用来获取QueryList,像是多个ViewChild组成的数组。

@ViewChildren(ChildDirective) viewChildren: QueryList<ChildDirective>;

ElementRef 与 ViewContainerRef

ViewChild可以使用 ElementRef 或者 ViewContainerRef 进行封装,那么 ElementRef 和 ViewContainerRef 的区别是什么?

用 ElementRef 进行封装,然后通过 .nativeElement 来获取原生Dom元素

console.log(this.customerRef.nativeElement.outerHTML);

ViewContainerRef :视图的容器,包含创建视图的方法和操作视图的api(组件与模板共同定义了视图)。api会返回 ComponentRef 与 ViewRef,那么这两个又是什么?

// 使用ViewContainetRef时,请使用read声明
@ViewChild('customerRef',{read: ViewContainerRef}) customerRef:ViewContainerRef;
···
this.customerRef.createComponent(componentFactory) // componentFactory之后会提到

ViewRef 与 ComponentRef

ViewRef 是最小的UI单元,ViewContainerRef api操作和获取的就是ViewRef

ComponentRef:宿主视图(组件实例视图)通过 ViewContainerRef 创建的对组件视图的引用,可以获取组件的信息并调用组件的方法

ComponentFactoryResolver

要获取 ComponentRef ,需要调用 ViewContainer 的 createComponent 方法,方法需要传入ComponentFactoryResolver创建的参数

constructor(
 private componentFactoryResolver:ComponentFactoryResolver
) { }

viewInit(){
  componentFactory = 
   this.componentFactoryResolver.resolveComponentFactory(DialogComponent);
  // 获取对组件视图的引用,到这一步就已经完成了组件的动态加载
  componentRef = this.customerRef.createComponent(componentFactory);
  // 调用载入的组件的方法
  componentRef.instance.dialogInit(component);
}

具体实现

let componentFactory,componentRef;

@ViewChild('customerRef',{read: ViewContainerRef}) customerRef:ViewContainerRef;
constructor(
 private componentFactoryResolver:ComponentFactoryResolver
) { }

viewInit(){
 // DialogComponent:你想要动态载入的组件,customerRef:动态组件存放的容器
  componentFactory = 
   this.componentFactoryResolver.resolveComponentFactory(DialogComponent);
  componentRef = this.customerRef.createComponent(componentFactory);
}

通过ngComponentOutlet实现动态载入

ngComponentOutlet 大大缩减了代码量,但是只有带4.0之后的版本才支持

具体实现

在dialog.component.html建立动态组件存放节点

<ng-container *ngComponentOutlet="componentName"></ng-container>

将组件(不是组件名称)传入,就OK了,为什么可以这么简单!

dialogInit(component){
  this.componentName = component;
};

Dialog的实现

实现的思路是这样的:首先创建一个dialog组件用来承载其他组件,为dialog创建遮罩和动画,建立一个service来控制dialog的生成和销毁,不过service只生成dialog,dialog内的组件还是需要在dialog组件内进行生成

1、首先写一个公共的service,用来获取根组件的viewContainerRef(尝试过 ApplicationRef 获取根组件的 viewContainerRef 没成功,所以就写成service了)

gerRootNode(...rootNodeViewContainerRef){
  if(rootNode){
   return rootNode;
  }else {
   rootNode = rootNodeViewContainerRef[0];
  };
}

// 然后再根组件.ts内调用
this.fn.gerRootNode(this.viewcontainerRef);

2、创建dialog.service.ts,定义open、close三个方法,使用ViewContainerRef创建dialog组件,创建之前需要调用 ComponentFactoryReslover,并将DialogComponent传入

let componentFactory;
let componentRef;

@Injectable()
export class DialogService {
 constructor(
    private componentFactoryResolver:ComponentFactoryResolver
    private fn:FnService
  ) { }   

 open(component){
  componentFactory = 
   this.componentFactoryResolver.resolveComponentFactory(DialogComponent);
  
  // 这里的获取的是ComponentRef
  containerRef = this.fn.gerRootNode().createComponent(componentFactory); 
  
  // 将containerRef存储下来,以便之后的销毁
  containerRefArray.push(containerRef);
  
  // 调用了组件内的初始化方法,后面会提到
  return containerRef.instance.dialogInit(component,containerRef);
 }

  // 这里有两种情况,一种是在当前组件和dialog组件关闭调用的,因为有返回值所以可以关闭指定的dialog;还有一种是在插入到dialog组件内的组件调用的,因为不知道父组件的信息,所以默认关闭最后一个dialog
 close(_containerRef=null){
  if( _containerRef ){
   return _containerRef.containerRef.instance.dialogDestory();
  }else{
   containerRefArray.splice(-1,1)[0].instance.dialogDestory();
  }
 }

}

3、dialog.component.ts,这里使用 ngComponentOutlet 来实现(ngComponentOutlet 在下面提到,这里为了偷懒,直接拿来用了)

let containerRef,dialogRef = new DialogRef();

export class DialogComponent implements OnInit {

 componentName;
 constructor(
  private fn:FnService
 ) { }

 dialogInit( _component, _containerRef){
  this.componentName = _component;
  containerRef = _containerRef;
  dialogRef['containerRef'] = containerRef;
  return dialogRef;
 };

 dialogDestory(){
  let rootNode = this.fn.gerRootNode();
  // 等待动画结束再移除
  setTimeout(()=>{
  // 这里用到了 viewContainerRef 里的indexOf 和 remove 方法
   rootNode.remove(rootNode.indexOf(containerRef.hostView));
  },400);
  dialogRef.close();
  return true;
 };
 
}

4、这里还创建了一个 DialogRef 的类,用来处理 dialog 关闭后的回调,这样就可以使用 XX.afterClose().subscribe() 来创建回调的方法了

@Injectable()
export class DialogRef{

 public afterClose$ = new Subject();
 constructor(){}

 close(){
  this.afterClose$.next();
  this.afterClose$.complete();
 }

 afterClose(){
  return this.afterClose$.asObservable();
 }

}

创建和销毁dialog

// 创建
let _viewRef = this.dialogService.open(DialogTestComponent);
_viewRef.afterClose().subscribe(()=>{
  console.log('hi');
});

// 销毁
this.dialogService.close()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
查看源码的工具 学习jQuery源码不错的工具
Dec 26 Javascript
javascript跑马灯悬停放大效果实现代码
Dec 12 Javascript
JavaScript获取DOM元素的11种方法总结
Apr 25 Javascript
jQuery中 delegate使用的问题
Jul 03 Javascript
JS利用cookie记忆当前位置的防刷新导航效果
Oct 15 Javascript
javascript for-in有序遍历json数据并探讨各个浏览器差异
Nov 30 Javascript
js 获取经纬度的实现方法
Jun 20 Javascript
vue2滚动条加载更多数据实现代码
Jan 10 Javascript
JS实现简单的星期格式转换功能示例
Jul 23 Javascript
微信小程序中上传图片并进行压缩的实现代码
Aug 28 Javascript
JS返回页面时自动回滚到历史浏览位置
Sep 26 Javascript
微信小程序视图控件与bindtap之间的问题的解决
Apr 08 Javascript
详解JavaScript中的数组合并方法和对象合并方法
May 11 #Javascript
Node.js使用cookie保持登录的方法
May 11 #Javascript
实例解析Vue.js下载方式及基本概念
May 11 #Javascript
AngularJS模态框模板ngDialog的使用详解
May 11 #Javascript
基于ionic实现下拉刷新功能
May 10 #Javascript
详解各版本React路由的跳转的方法
May 10 #Javascript
React路由管理之React Router总结
May 10 #Javascript
You might like
解决ajax+php中文乱码的方法详解
2013/06/09 PHP
用 Composer构建自己的 PHP 框架之设计 MVC
2014/10/30 PHP
php多次include后导致全局变量global失效的解决方法
2015/02/28 PHP
Javascript中的this绑定介绍
2011/09/22 Javascript
解析prototype,JQuery中跳出each循环的方法
2013/12/12 Javascript
jquery实现点击消失的代码
2014/03/03 Javascript
JS实现从连接中获取youtube的key实例
2015/07/02 Javascript
JS+CSS3模拟溢出滚动效果
2016/08/12 Javascript
jQuery操作css样式
2017/05/15 jQuery
让nodeJS支持ES6的词法----babel的安装和使用方法
2017/07/31 NodeJs
解决layui数据表格Date日期格式的回显Object的问题
2019/09/19 Javascript
Javascript原生ajax请求代码实例
2020/02/20 Javascript
使用Vue 自定义文件选择器组件的实例代码
2020/03/04 Javascript
[01:18:43]2014 DOTA2华西杯精英邀请赛5 24 iG VS DK
2014/05/25 DOTA
pymssql ntext字段调用问题解决方法
2008/12/17 Python
tensorflow入门之训练简单的神经网络方法
2018/02/26 Python
Python中GeoJson和bokeh-1的使用讲解
2019/01/03 Python
Python二维数组实现求出3*3矩阵对角线元素的和示例
2019/11/29 Python
详解Python 函数参数的拆解
2020/09/02 Python
Python全局变量与global关键字常见错误解决方案
2020/10/05 Python
python基于opencv实现人脸识别
2021/01/04 Python
装上这 14 个插件后,PyCharm 真的是无敌的存在
2021/01/11 Python
历史教育专业个人求职信
2013/12/13 职场文书
优秀毕业生自我鉴定
2014/01/19 职场文书
退伍老兵事迹材料
2014/01/31 职场文书
领班岗位职责范文
2014/02/06 职场文书
三月学雷锋月活动总结
2014/04/28 职场文书
初一新生军训方案
2014/05/22 职场文书
乡镇组织委员个人整改措施
2014/09/16 职场文书
团组织推优材料
2014/12/29 职场文书
《司马光》教学反思
2016/02/22 职场文书
小学教代会开幕词
2016/03/04 职场文书
nginx配置proxy_pass中url末尾带/与不带/的区别详解
2021/03/31 Servers
css3实现背景图片颜色修改的多种方式
2021/04/13 HTML / CSS
原生JS中应该禁止出现的写法
2021/05/05 Javascript
linux下导入、导出mysql数据库命令的实现方法
2021/05/26 MySQL