Injecting parent component with base class type in angular

Issue

I’m trying to inject my parent component into a child component (tight cupling, I know). The problem is I have an inheritance chain and for some reason I get an error, that there is no provider for the dependency.

tl;dr;

I’m injecting the base class in the child component, but I get the following error:
Template parse errors: No provider for BaseClass

export class BaseClass { ... }

@Component({ selector: 'parent-comp' })
export class ParentComponent extends BaseClass {}

@Component({ selector: 'child-comp' })
export class ChildComponent {
    constructor(public parent: BaseClass) {}
}

Usage:

<parent-comp>
   <child-comp>

The whys

My ParentComponent inherits some functionalities from the BaseClass and I would like to access some of it in the child component.
I’m building a library and there are more than one inherited components from BaseClass. I can’t tell which of the inherited components will be used, because the library consumer decides that.

I’ve tried adding the @Host() decorator but that doesn’t work either.

From my understanding of dependency injection (which is not the best) this should work. I’m trying to understand the why’s here!

If anyone could shed some light on the matter, I’d appreciate it!

Solution

If you want a child component to be displayed within a parent component, you add that child component’s selector to the parent component’s HTML. It is not designed to inject a component into another component.

If you have shared functionality, add that functionality to a service and use the service from both the parent and the child.

The communication between a parent and child should be limited to @input properties and @output events.

The purpose of a component is to display a user interface (some HTML). The purpose of the code within a component is to support the display of that HTML.

Use services to share properties/state or functionality/methods. Create a custom directive to share UI logic.

Answered By – DeborahK

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published