how to add and remove class in body with routing

App.component.ts

export class AppComponent implements OnInit {
  previousUrl: any;
  constructor(private render: Renderer2, private router: Router) {
    this.router.events.subscribe(
      (event) => {
        if (event instanceof NavigationStart) {
          //for current page name
          let currentUrlSlug = event.url.slice(1);
          if (this.previousUrl) {
            this.render.removeClass(document.body, this.previousUrl);
          }
          if (currentUrlSlug) {
            this.render.addClass(document.body, currentUrlSlug);
          }
          this.previousUrl = currentUrlSlug;
        }
      }
    )
  }

}

Leave a Reply

Your email address will not be published. Required fields are marked *