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

Time:07-11

@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!

CodePudding user response:

Even if you had access to the template HTML value, and added it via some [innerHtml] approach (which you can't as far as I know), it would render without bindings, directives etc - so wouldn't be of much use

It sounds like a separate shared component might be the way to go, one that uses ng-content to accept the host pages templates, and that shared component manages the loading/error/success states based on some inputs

CodePudding user response:

Not sure what you want to achieve by retrieving Angular's template, I'm answering your question as a general TypeScript question.

You could just store it in a variable like this:

function Component(arg: any) {
  return function <T>(clazz: T): T {
    return clazz;
  }
}

const template = '<div>hello</div>';

@Component({
  selector: 'base-comp',
  template
})
class BaseComponent {
    someMethod() {
      console.log(template);
    }
}

const obj = new BaseComponent;

obj.someMethod();

TypeScript playground

  • Related