Search code examples
angularcss-transitionsnavbarsticky

Angular sticky navbar without brutal transition


I have a problem when I put the navbar in "sticky" state, when I exceed the default position of the navbar it only reverts to its normal state when I am at the top of the page, which causes a "brutal" transition.

How can I do so as not to have this abrupt transition, no matter how hard I look, but I can't find any solution or it doesn't work.

Here is the stackblitz link which shows the preview (move the bar by hand and not with the wheel to really see the brutal effect): https://stackblitz.com/edit/angular-raebek?file=src/app


Solution

  • If you can use the built in CSS position: sticky, that will take care of it for you assuming you are ok with its compatibility https://developer.mozilla.org/en-US/docs/Web/CSS/position#Browser_compatibility

    Here's an udpated stack blitz https://stackblitz.com/edit/angular-oej69x?file=src/app/navbar/navbar.component.css

    We need to use angular's :host selector to set this style on the app-navbar element. It needs to be a block level element (Angular defaults to inline), have position: sticky and a top number of where you want it to stick, in our case 0. Then we get rid of all your JS class setting in the component scroll listner

    Add this to navbar.component.css

    /* we can use the built in CSS sticky feature, but we must do it on the app-navbar element so we use :host */
    :host {
      display: block;
      position: sticky; 
      top: 0;
    }