Using Intersection Observer for animations

63 views Asked by At

Im a rookie so maybe this is a dumb question, sorry in advance.

I want to create a website in angular and i want the content to be animated as it scrolls into the viewport. The 'solution' i found was intersection observer but unfortunately i cant get it to work. it seems like it just doesnt trigger as the elements scroll into the viewport.

I had some in depth discussions with chatGPT which werent helpful and i tried to google it but i only found solutions that work in plain js not in angular.

this is my typescript code:

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

@Component({
  selector: 'app-project-component',
  templateUrl: './project-component.component.html',
  styleUrls: ['./project-component.component.scss']
})
export class ProjectComponentComponent implements OnInit {
  projects = [project1, project2, project3, project4];
  @ViewChildren('hidden') myElements!: QueryList<ElementRef>;

  ngOnInit () {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        console.log(entry);
      });
    });

    this.myElements.forEach((el) => observer.observe(el.nativeElement));
  }
}

the projects array of course contains 4 json objects but i didnt want to bother you with more unnessecary details. i put the console log for debug reason, at this position i would write something like entry.target.classList.add('show'); to animate the content.

and here follows my html code:

<div class="project" *ngFor="let item of projects; let i = index" [ngClass]="{ 'odd': i % 2 == 1 }">
    <div class="img hidden">
        <img src="{{projects[i].img}}">
    </div>
    <div class="info hidden">
        <h1>{{projects[i].name}}</h1>
        <h3>{{projects[i].language}}</h3>
        <p>{{projects[i].description}}</p>
        <div class="links">
            <a href="{{projects[i].github}}" target="_blank">
                <button> Github </button>
            </a>
            <a href="{{projects[i].ftp}}" target="_blank">
                <button> Live test </button>
            </a>
        </div>
    </div>
</div>

If you have different suggestions for more effective 'on-scroll-animations' please let me know

Thanks for your time and help.

0

There are 0 answers