循环依赖是 Angular 中常见的问题之一,通常会导致应用程序崩溃或无法正常工作。其中一种情况是组件使用服务来动态创建相同类型的组件,从而导致循环依赖。
以下是解决此问题的步骤。
示例代码如下:
// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { DynamicComponent } from './dynamic.component'; @NgModule({ declarations: [AppComponent, DynamicComponent], imports: [BrowserModule], providers: [], bootstrap: [AppComponent] }) export class AppModule {}
// app.component.ts import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core'; import { DynamicComponent } from './dynamic.component'; @Component({ selector: 'app-root', template: '
' }) export class AppComponent { @ViewChild('dynamicComponent', {read: ViewContainerRef}) dynamicComponentContainer: ViewContainerRef; constructor(private componentFactoryResolver: ComponentFactoryResolver) {} createDynamicComponent() { const factory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent); const componentRef = this.dynamicComponentContainer.createComponent(factory); } }// dynamic.component.ts import { Component } from '@angular/core'; @Component({ selector: 'dynamic-component', template: '
I am a dynamic component!
' }) export class DynamicComponent {}下一篇:Angular循环引用与错误处理