Home > Blockchain >  Angular change header style when scrolling
Angular change header style when scrolling

Time:07-22

I want to add a style class when the user scroll the page and remove it when scroll position is to 0 but the style doesn't seems to be added...

Here is my onInit function in the header component that successfully add a class named viewstyle-opaque to header.

ngOnInit(): void {
    const header = document.querySelector('app-header');
    document.addEventListener('scroll', (ev) => {
      if (header !== null) {
        if (window.scrollY === 0) {
          header.classList.remove('viewstyle-opaque');
          return;
        }
        header.classList.add('viewstyle-opaque');
      }
    });
  }

My header component style, the other part is useless to paste here

.viewstyle-opaque {
    box-shadow: rgba(149, 157, 165, 0.3) 0px 4px 12px;
    background-color: #FFFFFF;
}

:host {
    padding: 0 25px 0 60px;
    width: 100%;
    height: 60px;
    position: fixed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    background-color: transparent;
    font-size: 16px;
...

enter image description here enter image description here

CodePudding user response:

Not sure as whole html is not available to see, but you have used pseudo-class :host and not provided specific place for it to be applied, so it may be taking precedence above other classes.

Example -

:host(.special-custom-element) {
  font-weight: bold;
}
  • Related