I'm trying to use intersection observer to add a class to some text after it passes a trigger point.
I confirmed that my observer was working when some of my text turned blue but some of my other texts that I want aren't turning blue. My trigger point should turn anything I want blue but it's not able to see some of the elements for some reason.
My console reads: Cannot read properties of undefined (reading 'classList')
HTML:
<div >
<div >
<div #text>
<span >Trigger</span>
<p>If font color is blue, trigger works for me</p>
</div>
<!-- <div ></div> -->
<div >If font color is blue, trigger works for me</div>
</div>
<div #choosePersonFade>
<div *ngFor="let info of list">
<div >
{{ info.name }}
</div>
</div>
</div>
</div>
TS:
export class AppComponent {
constructor(private el: ElementRef) {}
ngAfterViewInit() {
const threshold = 0.7;
const observer6 = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add('activate');
this.work.nativeElement.classList.add('activate'); //Doesn't work
// this.jerry.nativeElement!.classList.add('activate'); Doesn't work
// this.bob.nativeElement!.classList.add('activate'); Doesn't work
// this.matt.nativeElement!.classList.add('activate'); Doesn't work
}
});
},
{ threshold }
);
observer6.observe(this.text.nativeElement);
// observer6.observe(this.choosePersonFade.nativeElement);
}
@ViewChild('text') text!: ElementRef;
list = [
{
name: 'jerry',
},
{
name: 'matt',
},
{
name: 'bob',
},
];
get jerry() {
return this.el.nativeElement.querySelector('.jerry');
}
get matt() {
return this.el.nativeElement.querySelector('.matt');
}
get bob() {
return this.el.nativeElement.querySelector('.bob');
}
get work() {
return this.el.nativeElement.querySelector('.work');
}
}
CodePudding user response:
Here this.work represent DOM element.
this.work.classList.add('activate');