Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  97] [ 3]  / answers: 1 / hits: 24653  / 6 Years ago, thu, may 31, 2018, 12:00:00

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>

More From » angular

 Answers
12

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
}
}

[#54310] Sunday, May 27, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;