Search code examples
angularwebpackangular-standalone-components

Angular 15 Ref Error: Cannot access 'Component A' before initialization


I am facing one issue while importing standalone component within each other.

Component A.

@Component({
  standalone: true,
  selector: 'app-a',
  templateUrl: './a.component.html',
  styleUrls: ['./a.scss'],
  imports: [
    BComponent
  ]
})
export class AComponent implements OnInit {

}

Component B

@Component({
  standalone: true,
  selector: 'app-b',
  templateUrl: './b.component.html',
  styleUrls: ['./b.scss'],
  imports: [
    AComponent
  ]
})
export class BComponent implements OnInit {

}

Earlier this solution was working fine for me as accessing these components with using templates. but now getting this Error.

Ref Error: Cannot access 'AComponent' before initialization.

Any help in above context is highly appreciated.


Solution

  • Pick a component and use forwardRef

    @Component({
      standalone: true,
      selector: 'app-b',
      templateUrl: './b.component.html',
      styleUrls: ['./b.scss'],
      imports: [
        forwardRef(() => AComponent))
      ]
    })
    export class BComponent implements OnInit {
    
    }
    

    Stackblitz

    Credit to El Greco / Tim Deschryver, twitter thread