跳到正文
本页尚未翻译成中文,以下为英文原文。 查看英文版

Circular Dependency Detected ​

Angular detected a circular dependency between components, directives, or pipes. This error occurs when component A imports component B, and component B (directly or indirectly) imports component A, creating a cycle.

This circular reference prevents Angular from properly initializing the components, resulting in an error like:

text
NG0919: Cannot read @Component metadata. This can indicate a runtime circular dependency in your app that needs to be resolved.

In older Angular versions, you might instead see an error like:

text
Cannot read properties of undefined (reading 'ɵcmp')

Common Causes ​

Mutual Component Imports ​

The most common cause is when two components import each other:

ts
import {Component} from '@angular/core';
import {Child} from './child';

@Component({
  selector: 'app-parent',
  imports: [Child],
  template: '<app-child/>',
})
export class Parent {}
ts
import {Component} from '@angular/core';
import {Parent} from './parent';

@Component({
  selector: 'app-child',
  imports: [Parent],
  template: '<app-parent/>',
})
export class Child {}

Indirect Circular References ​

Circular dependencies can also occur through intermediate files:

text
ComponentA -> ComponentB -> ComponentC -> ComponentA

Resolving the error ​

Refactor shared logic ​

Move shared functionality to a separate file that doesn't import either component:

ts
import {Service} from '@angular/core';

@Service()
export class SharedService {
  // Shared logic here
}

Use type-only imports ​

If you only need types for TypeScript, use import type:

ts
import type {Parent} from './parent';

Type-only imports are erased at compile time and don't contribute to runtime circular dependencies.

Restructure component hierarchy ​

Consider whether the circular dependency indicates a design issue. Often, extracting shared functionality into a third component or service is the cleanest solution.

Debugging complex circular dependencies ​

For complex applications with many modules, circular dependencies can be difficult to identify manually. Consider using tools like madge to visualize and detect circular imports:

bash
# Install madge
npm install -g madge

# Check for circular dependencies
madge --circular --extensions ts ./src

# Generate a visual graph
madge --circular --extensions ts --image graph.svg ./src

These tools can help identify circular dependency chains across your entire project and generate visual dependency graphs.

基于 MIT 许可证发布。