简体   繁体   中英

Cannot use an abstract class Angular component in a module declaration

I have a base component class BaseComponent with its own markup, let's say this component is <base-component-fun> . Its markup is:

<div>
..Base markup
</div>

I export this component via module and reuse the library in other project when I inherit this component - and have its own markup + base component markup:

import { BaseComponent } from 'my-repository/base';

@Component({
  ...
})
export class InheritedComponent extends BaseComponent

with the markup:

<inherited-component-fun>
  ..Inherited markup
  <base-component-fun></base-component-fun>
</inherited-component-fun>

Here comes the problem: I MUST declare my base class BaseComponent in its module for export:

@NgModule({
  declarations: [BaseComponent],

otherwise the module is not built. But declaring an abstract class is not allowed.

What do I do? I've tried to find the solution in forums, but I could not. So I ended up by making base class non-abstract, which is not very good from design prospective - I want to have some abstract properties ih the base class.

By looking at your code, I see you are trying to render something like this.

component specific template
...
base class/component template
...
component specific template

This doesn't work with the way you are trying to do. You cannot render a class without declaring it in the module and you cannot declare an abstract one.

Possible solutions,

1. Use Content Projection - https://angular.io/guide/content-projection

Make the base class as parent and use the content projection to fill the required sections. You can put the child components here

2. Use complete template

If it is a simple structural change (may be like adding a card class etc), I would suggest you to just use the complete template again.

3. Use both abstract class and content projection

Use abstract class for the child component, and use a parent component with content projection to get the proper template.

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