Change Header on Scroll in Angular2 Typescript

As I was migrating from Angular 1.x to Angular 2, I needed to implement a header which changes its background when the page is scrolled somewhat similar to this fiddle fork. The basic idea is to change or apply a class on the header on the scroll event after some scrolling.

Now in Angular2 it is done on the same principal but a little bit differently. Here is what I came up with to do this.

First, create a component generally at the root level and assign a handler for the scroll event using the host property(or attribute or metadata) of the component as below:

@Component({
    selector: 'cubcode-app',
    templateUrl: './modules/welcome/templates/welcome.html',
    host: {
        '(window:scroll)': 'updateHeader($event)'
    }
})
export class AppComponent {
    isScrolled = false;
    currPos: Number = 0;
    startPos: Number = 0;
    changePos: Number = 100;

    constructor() {}

    updateHeader(evt) {
        this.currPos = (window.pageYOffset || evt.target.scrollTop) - (evt.target.clientTop || 0);
        if(this.currPos >= this.changePos ) {
            this.isScrolled = true;
        } else {
            this.isScrolled = false;
        }
    }
}

In the above code the updateHeader(evt) is the handler attached to the onscroll event on the window object.
The updateHeader method first calculates the current position of the scroll and then decides on the position at which the header to be changed. Here it only sets the isScrolled to true or false to denote that the header is ready to be updated or not.

Now using this Boolean value we can add or remove a CSS class for the header. Below is how I did it:

<header class="my-header" [ngClass]= "{'page-scroll-header': isScrolled}"></header>

So every time the page is scrolled up to or more than 100 pixels this class will be added to the header.

Now is the CSS we can specify the styling to give our header a new look as below:

.page-scroll-header {
    background-color: #ccc !important;
    opacity: 0.9;
}

That’s all what I did to update my header, but we can also add some transition to give the user good experience:

.my-header {
    transition: background-color 2s ease-out;
}

Now what if we don’t want to change the styling of our header, but want to add or remove a new element from it. For that too we can make use of the isScrolledvariable and use the *ngIf directive to add or remove any element. This way the element with *ngIf directive will be added if the page is scrolled up to or more than 100 pixels.