1

I need to manipulate a DOM element that is hidden by a *ngIf directive:

<div *ngIf="myBoolean">
    <canvas id="myElement"></canvas>
</div>

After a button click, I run the following method:

showMyElement(){
    this.myBoolean = true; //This shows the div containing myElement
    console.log(document.getElementById('myElement')); //This gives me null
}

But if I get myElement by clicking on another button after it is visible, I don't get null. I guess that when I get it the first time, it hasn't been added to the DOM yet. How can I know when myElement has been added to the DOM? Is there something like (ngModelChange) but for when added to the DOM? Thanks!

Akkusativobjekt
  • 1,957
  • 1
  • 19
  • 26
Pablo Quemé
  • 1,264
  • 4
  • 14
  • 29

1 Answers1

3

You can manually run change detection cycle to make sure that your view is updated

constructor(private cdRef: ChangeDetectorRef) {}

showMyElement(){
    this.myBoolean = true; 
    this.cdRef.detectChanges(); // redraw view
    console.log(document.getElementById('myElement')); //This gives me null
}

See also

Community
  • 1
  • 1
yurzui
  • 190,482
  • 29
  • 403
  • 383