Angular 5 生成 HTML 而不渲染

Ges*_*esh 1 html angular-components angular

是否可以通过绕过组件所需的所有数据来从组件生成 html 文件,而无需在浏览器视口中实际渲染它?我只想生成一些 html 代码,将其发送到后端,后端从该 html 生成 PDF。

Pit*_*Cat 5

我认为你不能,因为 Angular 组件的渲染很大程度上依赖于它的生命周期钩子。

不过,我可以想到一种伪造它的方法:

  • 从代码实例化一个不可见的组件
  • 将其添加到 DOM,因此它的行为就像任何常规组件一样
  • 检索它的 HTML
  • 并最终摧毁它

这是一个有效的代码示例

应用程序模块.ts

请注意,我已将其添加PdfContentComponententryComponents模块中。对于您想要从代码实例化的任何组件来说,这是必需的。

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

pdf-content.component.html

<span>Hello, {{ name }}</span>
Run Code Online (Sandbox Code Playgroud)

pdf-content.component.ts

请注意host: {style: 'display: none'},这会使组件实际上不可见

@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();
  }
}
Run Code Online (Sandbox Code Playgroud)

应用程序组件.html

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

<ng-container #pdfContainer>
</ng-container>
Run Code Online (Sandbox Code Playgroud)

应用程序组件.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));
    })
  }
}
Run Code Online (Sandbox Code Playgroud)