dimanche 10 juillet 2022

How to reference a component's own template defined in the @Component decorator?

@Component({
  selector: 'base-comp',
  template: '<div>hello</div>'  <-- how to get this
})
export class BaseComponent {
  someMethod( ) {
       <-- referenced here
  }

I know I can use ViewChild to select a child element, but I want the entire template.
Is there a way?

Use case context:
I have 20-30 components that all extend this base comp to use commonly shared functions like date parsing/formatting and such.
10-15 of those components all have the same loading & error state config code encompassing html,css,and ts.
I want to move them all to 1 place, so figured this shared base comp would work?
Idea is to define a constructor in the base class like this:

  constructor(
    private readonly selfRef?: ElementRef,
  ) {
    if (this.selfRef) {
       // attach this.template containing loading & error state html
       // via Renderer2 or .nativeElement or something
    }
  }

and attach it to the extender component's elementRef, thereby consolidating that bit of code into 1 place.
the css for this is a position: absolute overlay so it should just cover the extender comp.

Also open to alterative solutions for this effort.
Thanks!

Aucun commentaire:

Enregistrer un commentaire