Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular4 - Change style of header on scroll past 300px

I'm new on angular4, I'm looking for any tutorial that explains scroll. As the header states, I want to change the css properties of my header when I second past a particular position

Any help would be greatly appreciated. I have no idea where to start at all

like image 872
Davies Jeffrey Avatar asked Oct 08 '17 16:10

Davies Jeffrey


2 Answers

This is how I do it.

import { Component, OnInit } from '@angular/core';
import { PageEvent } from '@angular/material';
import { HostListener, Inject } from "@angular/core";
import { DOCUMENT } from '@angular/platform-browser';

declare const window: any;

@Component({
    selector: 'app-client-product-prev',
    templateUrl: './client-product-prev.component.html',
    styleUrls: ['./client-product-prev.component.css'],
})

export class IndexComponent implements OnInit {

  constructor(){

  }

  ngOnInit() {}


  // ===========================================================================
  // TRY THIS
  // ===========================================================================
  @HostListener("window:scroll", [])
  onWindowScroll() {

    const number = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
    if (number > 100) {
      console.log('You are 100px from the top to bottom');
    } else if (number > 500) {
        console.log('You are 500px from the top to bottom');
    }

  }




}
like image 50
George C. Avatar answered Sep 27 '22 02:09

George C.


Just weighing in on this one, as I had a similar desire today to shrink/enlarge text in my header bar as I scrolled. Very simple.

In my header.component.ts:

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

and then

@HostListener('window:scroll', [])
onWindowScroll() {
    const scrollOffset = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

    if (scrollOffset >= 120) {
        document.querySelectorAll('.controllable').forEach((c) => {
            c.classList.add('text-smaller');
            c.classList.remove('text-larger');
        });
    } else {
        document.querySelectorAll('.controllable').forEach((c) => {
            c.classList.add('text-larger');
            c.classList.remove('text-smaller');
        });
    }
}

in the HTML:

<span class="menu-link controllable">{{ link.label }}</span>

and in the CSS:

.menu-link.controllable.text-larger {
    font-size: 18px;
}

.menu-link.controllable.text-smaller {
    font-size: 14px;
}
like image 20
toby.harding Avatar answered Sep 24 '22 02:09

toby.harding