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
}
}
ngIf*="yourSubject | async"
, and in your .ts file you can put your display logic, or trigger some functions. – Biogen