Angular extending class with nested not exported class

573 Views Asked by At

Minimizing structure of my problem we have:

lib.module.ts (Module of library - wished to be unchanged)

@NgModule({
  declarations: [
   InternalComponent,
   ExternalComponent
  ],
  exports: [
   ExternalComponent
  ]
})
export class LibModule {}


external.component.ts

@Component({
    selector: 'external',
    template: '<internal></internal> We are in external',
    styles: ['']
})
export class ExternalComponent{}


internal.component.ts

@Component({
    selector: 'internal',
    template: 'This is internal',
    styles: ['']
})
export class InternalComponent{}

So my duty is to extend ExternalComponent. As far as I know we inherit only logic from typescript. Css and html has to be managed independently, in my case - copied and a little bit modified. However how can I copy html of ExternalComponent while InternalComponent isn't exported from LibModule?
Let's say ExternalExtendComponent is declared in AppModule. In AppModule I cannot import InternalComponent. So I cannot have template in ExternalExtendComponent with tag <internal>. Any idea of going through that?

2

There are 2 best solutions below

0
Michał Lis On BEST ANSWER

Simple solution might be writing my own module and don't use library's one. It would look like this: app.module.ts

import {InternalComponent,ExternalComponent} from 'myLib'; #myLib is in node_modules
import {TreeSelectExtComponent} from './tree-select-ext/tree-select-ext.component';

        @NgModule({
          declarations: [
           InternalComponent,
           ExternalComponent,
           ExternalExtComponent
          ]
        })
        export class AppModule{}

Important thing is that we cannot import LibModule anywhere in the project couse of double declarations.

4
Amit Chigadani On

You do not have to extend ExternalComponent actually, you can simply use external tag in your ExternalExtendComponent html file. This will copy the html of external inside it. This will also render internal component inside extended-external without exporting it from LibModule

See this small DEMO

EDIT :

To override external component, create a template reference (#ext) against external tag in extended-external-comp.

To inject styles, you can use Renderer2

Sample code

  @ViewChild('ext') ext : ElementRef

  constructor(private renderer : Renderer2 ) {
  }

  addStyles() {
    let animationState;
    let pEl = this.ext.nativeElement.querySelector('p')
    this.renderer.setStyle(pEl.nativeElement, '@ext', animationState);
  }