Trigger event when element becomes visible with ngIf

Manzur Khan picture Manzur Khan · May 31, 2018 · Viewed 17.9k times · Source

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>

Answer

user4676340 picture user4676340 · May 31, 2018

Your div will be rendered and visible once the change detection is triggered. When a change is detected, the whole lifecycle is ran again.

If you want to run something, you should hook on one of the events of the lifecycle. I suggest AfterViewInit.

Now that you know how, let's see what you should do.

In your case, you should create div with template references. This will allow you to have a reference to the element and make you able to check which div is shown or hidden.

Here is a stackblitz that shows you how it works, and here is the code :

import { Component, ViewChildren, QueryList, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <div *ngFor="let item of [0, 1, 2, 3, 4, 5]; let i = index">
    <span *ngIf="i === show" #shownDiv [id]="'div-' + i">{{ item }}</span>
  </div>
  `
})
export class AppComponent {
  name = 'Angular 6';
  show = 0;

  @ViewChildren('shownDiv') divs: QueryList<ElementRef>;

  ngOnInit() {
    setInterval(() => {
      this.show++;
      if (this.show > 5) {
        this.show = 0;
      }
    }, 1000);
  }

  ngAfterViewChecked() {
    let shown = this.divs.find(div => !!div);
    console.log('DIV shown is ' + (shown.nativeElement as HTMLSpanElement).id);
    // Now that you know which div is shown, you can run whatever piece of code you want
  }
}