简体   繁体   中英

Injecting parent component using class that parent component extends

I have multiple different angular components. Also there is a base list component in lots of these components.

For an example: VegetablesComponents has a BaseListComponent, FruitsComponent has BaseListComponent etc... Ofcourse there are different child components inside Vegetables/Fruits components as well.

BaseListComponent gets some data that modifies some functionalities from parent component (VegetablesComponent, FruitsComponent). This was done using @Input() on BaseListComponent.

So I got the idea that VegetablesComponent, FruitsComponent could extends same Class. And I could inject parent component inside BaseListComponent. Lets say:

VegetablesComponents extends HasBaseFunctionality {}

And then inside BaseListComponent I would use constructor(parent: HasBaseFunctionality,...).

This would reduce the numbers of inputs that would be needed on the BaseList component and it would make it look a lot cleaner.

But once I tried to do this I got the:

StaticInjectorError(AppModule)[ChildComponentComponent -> 
BaseComponentComponent]: 
StaticInjectorError(Platform: core)[ChildComponentComponent -> 
BaseComponentComponent]: 
NullInjectorError: No provider for BaseComponentComponent!

If I would use:

constructor(parent: VegetablesComponent) {...}

It would work.

So I was wondering if there was any way of doing this without using a service on which I would register the current base component once initializes and then access its values using service.

Each of your child components needs to provide the parent class:

@Component({
    providers: [
        {
            provide: BaseComponentComponent,
            useExisting: VegetablesComponent
       }
   ]
})

Then you can normally inject BaseComponentComponent type.

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