Search code examples
htmlangularclassdynamictags

Dynamic tag class in Angular17+


My navbar doesn't react on page change

My app.component.html

<html>
  <app-navbar></app-navbar>
  <router-outlet></router-outlet>
</html>

This tag starts my navbar.component.html segment

<nav class="navbar navbar-expand-md justify-content-center" + {{navType}}>

If it matters here is the idea on the component page
navType: string = "nav-other";

    if (this.router.url === '') { 
      this.navType = "navbar navbar-expand-md justify-content-center nav-splash";
    }

The following were tried:

<nav class="navbar navbar-expand-md justify-content-center + {{navType}}">
<nav [ngClass]={{navType}}> // With full class exchanged for editing one word
<nav [ngClass]="navType"> // With full class exchanged for editing one word

Solution

  • You need to use Angular's Router to listen for route changes and then update your navType.

    ngOnInit() {
        this.router.events.subscribe((event) => {
          if (event instanceof NavigationEnd) {
            if (event.url === '' || event.url === '/') {
              this.navType = 'nav-splash';
            } else {
              this.navType = 'nav-other';
            }
          }
        });
      }
    <nav class="..." [ngClass]="navType"></nav>

    Check this example on stackblitz