Home > Software design >  Can not use base class from shared module in Angular
Can not use base class from shared module in Angular

Time:01-31

I would like to use component from a shared module as a base class. Example:

// base.component.ts
@Component({ selector: 'app-base', ...})
export class BaseComponent {}
// shared.module.ts
import { CommonModule } from '@angular/common';
import { BaseComponent } from './base/base.component';

@NgModule({
  imports: [CommonModule],
  declarations: [BaseComponent],
  exports: [BaseComponent],
})
export class SharedModule {}
// app.module.ts
import { HelloComponent } from './hello.component';
import { SharedModule } from './shared/shared.module';

@NgModule({
  imports: [..., SharedModule],
  declarations: [AppComponent, HelloComponent],
  bootstrap: [AppComponent],
})
export class AppModule {}

This is ok (not my intended use):

// hello.component.ts
@Component({ template: `<app-base></app-base>` })
export class HelloComponent {}

This is not working (intended use):

// hello.component.ts
@Component({...})
export class HelloComponent extends BaseComponent {} // <-- Cannot find name 'BaseComponent'

Does angular allow using the base class in the above simple way? Or is my intended use wrong and some other approach needs to be used?

CodePudding user response:

First of all, using a sharedModule is often an old bad practice, better to use SCAM (Single Component Angular Module) or Standalone Components.

Anyway, if you want to extend BaseComponent, you can do it, but you have to import it import { BaseComponent } from './base/base.component'; if you don't intend to use the BaseComponent itself, there is no need to declare it in any module, you just need to declare the HomeComponent

CodePudding user response:

View this complete tutorial.

Use the component from the shared module as a base class in your child component:

In the “child.component.ts” file, extend the base component using the extends keyword:

import { Component } from '@angular/core';
import { BaseComponent } from '../shared/base/base.component';

@Component({
  selector: 'app-hello',
  template: `
    <app-base></app-base>
    <p>Hello Component works!</p>
  `
})
export class HelloComponent  extends BaseComponent {
  constructor() {
    super();
  }
}

Make sure that you are using the selector of the parent component in the appropriate template file.

Use the hello component anywhere in your template: In the template where you want to use the hello component, include the hello component using its selector:

<app-hello></app-hello>
  • Related