Gesh
Gesh

Reputation: 575

Angular 5 generate HTML without rendering

Is it possible to generate a html file from a component by bypassing all the data it needs without actually rendering it in the browser viewport? I would like to just generate some html code to send it to the backend that generates a PDF from this html.

Upvotes: 2

Views: 3774

Answers (2)

Vikash Dahiya
Vikash Dahiya

Reputation: 5801

You can use Renderer2 class provided by angular. Try this sample code;

import { Component, Renderer2, OnInit } from '@angular/core';

....

constructor(private renderer: Renderer2){

}

ngOnInit(){
  const div: HTMLDivElement = this.renderer.createElement('div');
  const text = this.renderer.createText('Hello world!');
  this.renderer.appendChild(div, text);
  console.log(div.outerHTML);
}

Upvotes: 3

PitchBlackCat
PitchBlackCat

Reputation: 555

I don't think you can, since rendering of angular's components relies heavily on it's lifecycle hooks.

I can think of one way to fake it, though, by:

  • instantiating an invisible component from code
  • add it to the DOM, so it behaves like any regular component
  • retrieve it's HTML
  • and finally destroy it

Here's a working code example.

app.module.ts

Notice that i've added PdfContentComponent to the entryComponents of the module. This is required for any component that you want to instantiate from code.

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, PdfContentComponent ],
  bootstrap:    [ AppComponent ],
  entryComponents :  [ PdfContentComponent ]
})
export class AppModule { }

pdf-content.component.html

<span>Hello, {{ name }}</span>

pdf-content.component.ts

Notice the host: {style: 'display: none'}, this renders the component effectivly invisible

@Component({
  selector: 'my-pdf-content',
  templateUrl: './pdf-content.component.html',
  host: {
    style: 'display: none'
  }
})
export class PdfContentComponent implements OnInit  {
  @Input() name: string;
  @Output() loaded: EventEmitter<void> = new EventEmitter<void>();

  constructor(public element:ElementRef) {

  }

  ngOnInit() {
    this.loaded.emit();
  }
}

app.component.html

<button (click)='printPdf()'>Hit me!</button>

<ng-container #pdfContainer>
</ng-container>

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

// the pdf content will be briefly added to this container
@ViewChild("pdfContainer", { read: ViewContainerRef }) container;

constructor(
  private resolver: ComponentFactoryResolver
) {}

  printPdf() {
    // get the PdfContentComponent factory
    const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(PdfContentComponent);

    // instantiate a PdfContentComponent
    const pdfContentRef = this.container.createComponent(factory);

    // get the actual instance from the reference
    const pdfContent = pdfContentRef.instance;

    // change some input properties of the component
    pdfContent.name = 'John Doe'; 

    // wait for the component to finish initialization
    // and delay the event listener briefly, 
    // so we don't run the clean up in the middle of angulars lifecycle pass
    const sub = pdfContent.loaded
    .pipe(delay(1))
    .subscribe(() => {
        // stop listening to the loaded event
        sub.unsubscribe();
        // send the html to the backend here
        window.alert(pdfContent.element.nativeElement.innerHTML);
        // remove the component from the DOM
        this.container.remove(this.container.indexOf(pdfContentRef));
    })
  }
}

Upvotes: 5

Related Questions