0

I'm looking for a way to set HTML style in dynamic table initialized with *ngFor when my table is totally initialized.
I tried ngAfterViewInit, ngAfterContentInit but not working. When I log my element (console.log(document.getElementById(my_tr_id)) in this functions, it still null.

Any ideas?

Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48

2 Answers2

0

You can use @ViewChildren for that purpose

 <ul>
      <li class="list" #allTheseThings *ngFor="let i of items; let last = last">{{i}}</li>
 </ul>

and then listen to this in your ts:

ngAfterViewInit() {

    this.things.changes.subscribe(t => {
      this.ngForRendred();
    ...
    })
  }

my example: https://stackblitz.com/edit/angular-2t19gf?file=src%2Fapp%2Fapp.component.ts

origional Answer is here: execute a function when *ngFor finished in angular 2

BartoszTermena
  • 1,487
  • 1
  • 8
  • 16
0

You can simply achieved it the way you have written code, not sure why your instance is not working.

I have added the code in below snippet where you can see the required changes.

You can also see working stackblitz here: https://stackblitz.com/edit/angular-pvepzg

import {
  Component
} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dataId = 2;
  activeDatasChecklist = [{
    id: 1,
    name: 'data 1',
  }, {
    id: 2,
    name: 'data 2',
  }, {
    id: 3,
    name: 'data 3',
  }, {
    id: 4,
    name: 'data 4',
  }, ]

  addNew() {
    this.activeDatasChecklist.push({
      id: 2,
      name: 'new addition'
    })
  }
}
.focus {
  background-color: yellow;
}
<table>
  <tbody>
    <tr *ngFor="let data of activeDatasChecklist" [ngClass]="{'focus':data.id === dataId}">
      <td>{{data.name}}</td>
      <td>{{data.id}}</td>
    </tr>
  </tbody>
</table>

<button (click)="addNew()">Add new</button>
Jasdeep Singh
  • 7,901
  • 1
  • 11
  • 28