Search code examples
angularurlroutesangular-routing

how to change class dynamically with url change in Angular


I got a dashboard component on app.html and I want to display everything inside it except when it's sign-in or sign-up URL. So I'm trying to dynamically add/remove a class defined as main__hidden which makes a block to display: none based on the URL. But for some reason, it's not working. I've tried defining the styles in global style.css as well but it didn't work.

app.html

     <app-main *ngIf="showNavbar">
    
      <router-outlet></router-outlet>
    
    </app-main>

app.ts

    export class AppComponent {
      title = 'frontend';
      public showNavbar: boolean = false
    
      constructor(private router: Router) {
        // Removing Sidebar, Navbar, Footer for Documentation, Error and Auth pages
        router.events.forEach((event) => {
          if (event instanceof NavigationStart) {
            if ((event['url'] == '/sign-in') || (event['url'] == '/sign-up')) {
              this.showNavbar = false;
              let body = document.querySelector('body');
              body.classList.add('main__hidden');
            }
          } else {
            this.showNavbar = true;
            let body = document.querySelector('body');
            body.classList.remove('main__hidden');
          }
        });
    
      }
    }

main.css

    .main__header {
      z-index: 1;
      position: fixed;
      background: #22242a;
      padding: 20px;
      width: calc(100% - 0%);
      top: 0;
      height: 30px;
      display: block;
    }
    .main__sidebar {
      z-index: 1;
      top: 0;
      background: #2f323a;
      margin-top: 70px;
      padding-top: 30px;
      position: fixed;
      left: 0;
      width: 250px;
      height: 100%;
      transition: 0.2s;
      transition-property: left;
      overflow-y: auto;
      display: block;
    }
    :host-context(.main__hidden) .main__sidebar {
      display: none;
    }
    
    :host-context(.main__hidden) .main__header {
      display: none;
    }

Solution

  • make a method showMain() inside main.ts and and call it inside constructor

      public showMain = () => {
        this.router.events.forEach((event) => {
          if (event instanceof NavigationStart) {
            if ((event['url'] == '/sign-in') || (event['url'] == '/sign-up')) {
              this.hideMain = false;
              document.querySelector('.main__header').classList.add('main__hidden');
              document.querySelector('.main__sidebar').classList.add('main__hidden');
            } else {
              this.hideMain = true;
              document.querySelector('.main__header').classList.remove('main__hidden');
              document.querySelector('.main__sidebar').classList.remove('main__hidden');
            }
          }
        });
      }```