2

I am trying to create pdf from server side using angular 2 apps by sending HTML content to the server using ElementRef but It sends only HTML part not angular binding part.I also want to add CSS part in my HTML contents.So I want to know ElementRef is the best way or I should try anything else.

Component.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;
  }

}

It only send following data:

<table class="table table-striped">
    <thead>
    <tr>
      <th>username</th>
      <th>email</th>
      <th>name</th>
    </tr>
    </thead>
    <tbody>
    <!--template bindings={}-->
    </tbody>
  </table>

And I want to send like

<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>
Rahul dev
  • 1,267
  • 3
  • 18
  • 31

1 Answers1

2

You're using the wrong hook. You need to wait for view to initialize. That's when your *ngFor will be resolved and proper content will be placed in the view.

ngAfterViewInit() {
  this.node = this.elementRef.nativeElement.innerHTML;
}
Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91