简体   繁体   中英

Injecting parent component with base class type in angular

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!

It is not "best practice" to attempt to insert a parent component into a child 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.

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 does not make any sense (and it is not designed that way) to inject a component into another component.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM