Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading