Get the raw HTML template for an Angular component

149 Views Asked by At

We are creating a library of shared Angular components. I'd like to document this shared component library which means that we are creating a web project that contains and displays all of those components and code examples as to how to use them.

I had a working version for angular 8 that does not seem to work in angular 15.

I would like to find a way to be able to read the raw(not DOM translated) HTML template for a given component. I had a working version for Angular 8. I was using the following

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.scss'],
})
export class ExampleComponent implements OnInit, AfterContentChecked {

  ...

  @ContentChild('example') template;

  ...

   ngAfterContentChecked(): void {
    if (this.template && this.isBrowser) {
      let code = this.getAnnotation(this.template.constructor);
    }
  }

  getAnnotation(typeOrFunc: Type<any>): { template: string } | null {
    // Prefer the direct API.
    if ((<any>typeOrFunc)['__annotations__']) {
      return (<any>typeOrFunc)['__annotations__'][0];
    }

    // API of tsickle for lowering decorators to properties on the class.
    if ((<any>typeOrFunc).decorators) {
      return this.convertTsickleDecoratorIntoMetadata((<any>typeOrFunc).decorators)[0];
    }

    // API for metadata created by invoking the decorators.
    if (Reflect && Reflect.getOwnMetadata) {
      return Reflect.getOwnMetadata('annotations', typeOrFunc)[0];
    }
    return null;
  }

  convertTsickleDecoratorIntoMetadata(decoratorInvocations: any[]): any[] {
    if (!decoratorInvocations) {
      return [];
    }
    return decoratorInvocations.map((decoratorInvocation) => {
      const decoratorType = decoratorInvocation.type;
      const annotationCls = decoratorType.annotationCls;
      const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];
      return new annotationCls(...annotationArgs);
    });
  }
}
 <app-example title="X Large">
    <app-button-primary-example1 #example></app-button-primary-example1>
 </app-example>

Based on the SO answer from here

Is there a way to get the HTML template for an Angular* component? since then we've upgraded to angular 15 and this no longer works. Everything related to the annotations property seems to be undefined.

Does anyone have a way of achieving above as it would greatly reduce the amount of manual HTML string management that is likely to end up being out of date.

0

There are 0 best solutions below