经测试,动态创建组件和路由有干扰,去掉路由后动态创建组件工作正常。
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>