1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > angular动态创建组件的服务代码

angular动态创建组件的服务代码

时间:2023-10-27 23:46:12

相关推荐

angular动态创建组件的服务代码

经测试,动态创建组件和路由有干扰,去掉路由后动态创建组件工作正常。

dynamic-create.service.ts

这个服务可以在任何容器内创建任何组件。创建之前会清空容器。

import {Injectable, ViewContainerRef, ComponentFactory, ComponentRef, ComponentFactoryResolver, Type } from '@angular/core';@Injectable({providedIn: 'root'})export class DynamicCreateService {constructor(private resolver: ComponentFactoryResolver) {}createComponent<componentType>(container: ViewContainerRef, component: Type<componentType>): ComponentRef<componentType> {container.clear();const factory: ComponentFactory<componentType> =this.resolver.resolveComponentFactory<componentType>(component);return container.createComponent(factory);}}

用法:

ponent.ts

@Component({selector: 'app-root',templateUrl: './ponent.html',styleUrls: ['./ponent.scss'],encapsulation: ViewEncapsulation.None})export class AppComponent implements OnInit, AfterViewInit {@ViewChild('viewContainer', {read: ViewContainerRef }) container: ViewContainerRef;componentRef: ComponentRef<any>;constructor(private dcs: DynamicCreateService,) {}ngAfterViewInit(): void {if (sessionStorage.getItem('userToken')) {this.createHomePage();} else {this.createLoginPage();}}createLoginPage() {ponentRef = this.dcs.createComponent(this.container, LoginComponent);(ponentRef.instance as LoginComponent).login.subscribe(() => this.createHomePage());}createHomePage() {ponentRef = this.dcs.createComponent(this.container, HomeComponent);}}

ponent.html

<ng-template #viewContainer></ng-template>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。