search
HomeWeb Front-endJS TutorialHow to use Angular to implement Dialog using dynamic loading component method

This time I will show you how to operate Angular and use the dynamic loading component method to implement Dialog. How to operate Angular and use the dynamic loading component method to implement Dialog. What are the precautions?The following is a practical case, let’s take a look .

The articles and tutorials on the Internet basically stop after the component is loaded! Gone? ! And there can only be one dialog. If you want to open another dialog, you must first destroy the currently opened dialog. After seeing the implementation of material, I blame myself for being too stupid to understand the source code, so I can only implement it in my own way. The dialog component is

The goal of the Dialog component: multiple Dialogs can exist at the same time, and the specified Dialog can be destroyed. After destruction, no components remain in the HTML and callbacks are provided.

There are two ways to implement dynamic loading of components. Before version 4.0 of angular, ComponentFactoryResolver was used to implement it. After 4.0, the more convenient ngComponentOutlet can be used to implement it.

Dynamic loading is achieved through ComponentFactoryResolver

First sort out the relationship between ViewChild, ViewChildren, ElementRef, ViewContainerRef, ViewRef, ComponentRef, and ComponentFactoryResolver:

ViewChild and ViewChildren

ViewChild is referenced through the template Variable (#) or directive (directive) is used to obtain Angular Dom Abstract class, ViewChild can be encapsulated using ElementRef or ViewContainerRef.

@ViewChild('customerRef') customerRef:ElementRef;

ViewChildren is used to obtain QueryList through template reference variables or instructions, such as an array composed of multiple ViewChilds.

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

ElementRef and ViewContainerRef

ViewChild can be encapsulated using ElementRef or ViewContainerRef. So what is the difference between ElementRef and ViewContainerRef?

Encapsulate with ElementRef, and then obtain the native Dom element through .nativeElement

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

ViewContainerRef: the container of the view, including the method of creating the view and the API for operating the view (the component and the template are jointly defined view). The api will return ComponentRef and ViewRef, so what are these two?

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

ViewRef and ComponentRef

ViewRef is the smallest UI unit. ViewContainerRef api operates and obtains ViewRef

ComponentRef: host view (component instance View) Through the reference to the component view created by ViewContainerRef, you can obtain the component information and call the component's method

ComponentFactoryResolver

To obtain the ComponentRef, you need to call createComponent of ViewContainer Method, the method needs to pass in the parameters created by ComponentFactoryResolver

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

Specific implementation

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);
}

Achieve dynamic loading through ngComponentOutlet

ngComponentOutlet greatly reduces the amount of code, but only versions after 4.0 are supported

Specific implementation

Create a dynamic component storage node in dialog.component.html

<ng-container></ng-container>

Pass in the component (not the component name) and it will be OK. Why can it be so simple!

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

Dialog implementation

The implementation idea is as follows: first create a dialog component to host other components, and create a mask for the dialog. Cover and animation, create a service to control the generation and destruction of dialog, but the service only generates dialog, the components in the dialog still need to be generated in the dialog component

1. First, write a public service to Get the viewContainerRef of the root component (I tried ApplicationRef to get the viewContainerRef of the root component but failed, so I wrote it as service)

gerRootNode(...rootNodeViewContainerRef){
  if(rootNode){
   return rootNode;
  }else {
   rootNode = rootNodeViewContainerRef[0];
  };
}
// 然后再根组件.ts内调用
this.fn.gerRootNode(this.viewcontainerRef);

2. Create dialog.service.ts, define three methods of open and close, and create it using ViewContainerRef Before creating the dialog component, you need to call ComponentFactoryReslover and pass the DialogComponent into

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. Here, ngComponentOutlet is used to implement it (ngComponentOutlet is mentioned below. For the sake of laziness, it is used directly. )

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()

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样操作Node.js 使用jade模板引擎

Node.js Express安装与使用详细介绍

The above is the detailed content of How to use Angular to implement Dialog using dynamic loading component method. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
聊聊Angular中的元数据(Metadata)和装饰器(Decorator)聊聊Angular中的元数据(Metadata)和装饰器(Decorator)Feb 28, 2022 am 11:10 AM

本篇文章继续Angular的学习,带大家了解一下Angular中的元数据和装饰器,简单了解一下他们的用法,希望对大家有所帮助!

angular学习之详解状态管理器NgRxangular学习之详解状态管理器NgRxMay 25, 2022 am 11:01 AM

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

浅析angular中怎么使用monaco-editor浅析angular中怎么使用monaco-editorOct 17, 2022 pm 08:04 PM

angular中怎么使用monaco-editor?下面本篇文章记录下最近的一次业务中用到的 monaco-editor 在 angular 中的使用,希望对大家有所帮助!

项目过大怎么办?如何合理拆分Angular项目?项目过大怎么办?如何合理拆分Angular项目?Jul 26, 2022 pm 07:18 PM

Angular项目过大,怎么合理拆分它?下面本篇文章给大家介绍一下合理拆分Angular项目的方法,希望对大家有所帮助!

聊聊自定义angular-datetime-picker格式的方法聊聊自定义angular-datetime-picker格式的方法Sep 08, 2022 pm 08:29 PM

怎么自定义angular-datetime-picker格式?下面本篇文章聊聊自定义格式的方法,希望对大家有所帮助!

Angular + NG-ZORRO快速开发一个后台系统Angular + NG-ZORRO快速开发一个后台系统Apr 21, 2022 am 10:45 AM

本篇文章给大家分享一个Angular实战,了解一下angualr 结合 ng-zorro 如何快速开发一个后台系统,希望对大家有所帮助!

聊聊Angular Route中怎么提前获取数据聊聊Angular Route中怎么提前获取数据Jul 13, 2022 pm 08:00 PM

Angular Route中怎么提前获取数据?下面本篇文章给大家介绍一下从 Angular Route 中提前获取数据的方法,希望对大家有所帮助!

浅析Angular中的独立组件,看看怎么使用浅析Angular中的独立组件,看看怎么使用Jun 23, 2022 pm 03:49 PM

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment