angularsvgdynamicsrc

How can i change homepage icon svg to solid in Angular app?


I have a sidebar component and there is a navigation menu inside it with some buttons. This is button component HTML template:

    <a
    routerLink="{{ data[index].href }}"
    class="container__button"
    routerLinkActive="active">
    <img
      [src]="
        isActive(data[index].class) ? data[index].srcActive : data[index].src
      "
      alt="{{ data[index].alt }}"
      class="container__svg {{ data[index].class }}" />
    <p class="container__text">{{ data[index].btnText }}</p>
  </a>
</div>

In [src] attribute i insert ternary operator in which i use isActive method that i defined in TypeScript template. Here is the code:

    export class SidebarButtonComponent implements OnInit {
  private readonly router = inject(Router)
  private readonly sidebar = inject(SidebarService)
  @Input() index = 0
  data = {} as SidebarButton[]
  ngOnInit(): void {
    this.data = this.sidebar.getData()
  }
  isActive(route: string): boolean {
    return this.router.isActive(route, {
      paths: 'exact',
      queryParams: 'ignored',
      fragment: 'ignored',
      matrixParams: 'ignored',
    })
  }
}

I get data from service that i've created. And i have routes file which looks like this:

    export const routes: Routes = [
  {
    path: ' ',
    component: HomepageComponent,
  },
]

So i need to change SVG icon in homepage when i'm in route: paht: ''. How can i modify that method isActive()?


Solution

  • We can check the url property of angular router and confirm it equals to /.

    export class AppComponent {
      private router = inject(Router);
      private route = inject(ActivatedRoute);
      isActive(): boolean {
        return this.router.url === '/';
      }
    }
    

    Stackblitz Demo