Error Encyclopedia

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:

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:

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

Common Causes

Mutual Component Imports

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

parent.component.ts

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

child.component.ts

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

Indirect Circular References

Circular dependencies can also occur through intermediate files:

ComponentA -> ComponentB -> ComponentC -> ComponentA

Resolving the error

Refactor shared logic

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

shared.service.ts

import {Injectable} from '@angular/core';@Injectable({providedIn: 'root'})export class SharedService {  // Shared logic here}

Use type-only imports

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

import type {ParentComponent} from './parent.component';

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:

# Install madgenpm install -g madge# Check for circular dependenciesmadge --circular --extensions ts ./src# Generate a visual graphmadge --circular --extensions ts --image graph.svg ./src

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