Angular Show and hide div when scroll to specific section

<!-- app.component.html -->

<!-- Target Section -->
<div #targetDiv class="section">
  <h2>Target Section</h2>
  <p>This section will trigger the visibility of the element below when it reaches the top.</p>
</div>

<!-- Element to show when the target div reaches the top -->
<div *ngIf="showElement" class="show-element">
  <h3>This element is now visible!</h3>
</div>

In your ts file.

import { Component, ViewChild, ElementRef, HostListener } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('targetDiv') targetDiv: ElementRef;
  showElement = false;

  // Listen for scroll events
  @HostListener('window:scroll', ['$event'])
  onScroll(event: Event): void {
    this.checkSectionPosition();
  }

  // Check if the target section has reached the top
  private checkSectionPosition() {
    const targetDivPosition = this.targetDiv.nativeElement.getBoundingClientRect();
    if (targetDivPosition.top <= 0 && targetDivPosition.bottom >= 0) {
      // When the target div is at the top of the viewport, show the element
      this.showElement = true;
    } else {
      // Hide the element when the target div is not at the top
      this.showElement = false;
    }
  }
}
CSS (optional):

Leave a Reply

Your email address will not be published. Required fields are marked *