Home >Web Front-end >JS Tutorial >How 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>;
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 *ngComponentOutlet="componentName"></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中文网其它相关文章!
推荐阅读:
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!