Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger event when element becomes visible with ngIf

I'm having some divs with ngIf, I just want to have a way to know if the particular div is the one which is visible/active right now like an event trigger like focus (it doesn't work) or something, and with this event, I will set a variable or something.

<div *ngIf="test === true" (focus)="myVariable = true">
</div>
like image 334
Manzur Khan Avatar asked May 31 '18 06:05

Manzur Khan


1 Answers

I would like to build on Rachit's answer.

<div *ngIf="test"><ng-container *ngIf="runShow && show()"></ng-container></div>

and in the component

this.runShow = true;

//show always returns true.
show() {
  //Return if not running. Shouldn't be needed as runShow proceeds show in the template.
  if(!this.runShow) {
    return true;
  }
  //Do modifications...

  this.runShow = false;
  return true;

show() will only run if test is truthy, and will turn itself off after a single iteration (of course, you can change this.runShow to be based off something). An important gotcha is that until this.runShow == false, this will run every time the component detects a change, no more and no less. We put the show() inside its own ng-container so that it doesn't impact the DOM and is run after the test is rendered.

like image 88
Cameron Burger Avatar answered Oct 07 '22 17:10

Cameron Burger