Angular – Dependency Injection: Cannot read properties of undefined

I am attempting to access a property (observable$) of a child component (ChildComponent) from a parent component (ParentComponent). However, I’m getting the error: Cannot read properties of undefined.

app.module.ts

@NgModule({
  declarations: [
    ParentComponent,
    ChildComponent
  ],
  providers: [
    {provide: ParentComponent, deps: [ChildComponent]}
  ]
})

parent.component.ts

@Component({})
export class ParentComponent implements AfterViewInit {
  constructor(private childComponent: ChildComponent) {
  }

  ngAfterViewInit() {
    this.childComponent.observable$.subscribe(() => {}
  }
}

child.component.ts

@Component({})
@Injectable({ providedIn: 'root' })
export class ChildComponent implements AfterViewInit {

  @ViewChild("myElement") element: ElementRef<Element>;
  observable$: Observable<any>;

  constructor() { }

  ngAfterViewInit(): void {
    this.observable$ = fromEvent(this.element.nativeElement, "click");
  }

}

I expected the properties of the child component to be accessible to the parent component.

>Solution :

You can’t have a child component in dependency injection.

You will need to use a @ViewChild() decorator.

@Component({})
export class ParentComponent implements AfterViewInit {
  @ViewChild(ChildComponent) childComponent: ChildComponent)

  ngAfterViewInit() {
    this.childComponent.observable$.subscribe(() => {}
  }
}

Also @Injectable() makes no sense on a component, you should remove that.

Leave a Reply