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

用法:
app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.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() {
    this.componentRef = this.dcs.createComponent(this.container, LoginComponent);
    (this.componentRef.instance as LoginComponent).login.subscribe(() => this.createHomePage());
  }

  createHomePage() {
    this.componentRef = this.dcs.createComponent(this.container, HomeComponent);
  }
}

app.component.html

<ng-template #viewContainer>ng-template>

你可能感兴趣的:(前端)