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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools