将HTML内容发送到服务器以创建PDF Angular 2

3
我可以帮您翻译,这段文本是关于使用 Angular 2 应用从服务器端创建 PDF,并通过 ElementRef 发送 HTML 内容到服务器。但它只发送 HTML 部分而不是 Angular 绑定部分。我还想在我的 HTML 内容中添加 CSS 部分,所以我想知道 ElementRef 是否是最佳方法,或者是否应该尝试其他方法。
组件.ts
import { AfterContentInit, Component, ElementRef } from '@angular/core';

@Component({
    selector: 'app-root',
    template: `
    <table>
    <thead>
    <tr>
      <th>username</th>
      <th>email</th>
      <th>name</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let data of data">
      <td>{{ data.username }}</td>
      <td>{{ data.email }}</td>
      <td>{{ data.first_name }}</td>
    </tr>
    </tbody>
  </table>`
})

export class AppComponent implements AfterContentInit {
  node: string;

  data = [
    {
      "id": 11,
      "username": "abc",
      "email": "abc@gmail.com",
      "first_name": "ramesh"

    },
    {
      "id": 13,
      "username": "btest",
      "email": "btest@gmail.com",
      "first_name": "btest"

    },
    {
      "id": 14,
      "username": "abcd",
      "email": "abcd@gmail.com",
      "first_name": "abcd"

    },
    {
      "id": 15,
      "username": "demotest",
      "email": "demotest@gmail.com",
      "first_name": "demotest",
      "last_name": "demo"

    }
  ]

  constructor(private elementRef: ElementRef) { }

  ngAfterContentInit() {
   this.node = this.elementRef.nativeElement.innerHTML;
  }

}

它只发送以下数据:
<table class="table table-striped">
    <thead>
    <tr>
      <th>username</th>
      <th>email</th>
      <th>name</th>
    </tr>
    </thead>
    <tbody>
    <!--template bindings={}-->
    </tbody>
  </table>

我想要发送类似的内容

<table class="table table-striped">
    <thead>
    <tr>
      <th>username</th>
      <th>email</th>
      <th>name</th>
    </tr>
    </thead>
    <tbody>
    <!--template bindings={
  "ng-reflect-ng-for-of": "[object Object],[object Object],[object Object],[object Object]"
}--><tr>
      <td>abc</td>
      <td>abc@gmail.com</td>
      <td>ramesh</td>
    </tr><tr>
      <td>btest</td>
      <td>btest@gmail.com</td>
      <td>btest</td>
    </tr><tr>
      <td>abcd</td>
      <td>abcd@gmail.com</td>
      <td>abcd</td>
    </tr><tr>
      <td>demotest</td>
      <td>demotest@gmail.com</td>
      <td>demotest</td>
    </tr>
    </tbody>
  </table>

https://dev59.com/oHRB5IYBdhLWcg3wCjcV#778897 - undefined
1个回答

2

你使用了错误的钩子。你需要等待视图初始化。这时,你的*ngFor将被解析,并且适当的内容将放置在视图中。

ngAfterViewInit() {
  this.node = this.elementRef.nativeElement.innerHTML;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接