Search code examples
angularangular-routing

How to use routerlinkactive with a function


I have a simple component that uses routerlinkactive and depending on what the function returns, I want to put one style or another:

The component file:

import { Component, Input } from '@angular/core';
import { Route, ActivatedRoute, Router, RouterLinkActive } from 
'@angular/router';

@Component({
  selector: 'app-sel',
  template: `
   <a [routerLink]="routeUrl" routerLinkActive="esAplicacionCopiadoras() ? 
  'colorCopiadoras' : 'colorSolicitudes'" ></a> `
  styleUrls: ['./submenu.component.css']
})

export class NavItemComponent {
   private aplicacion:bool =true;
     esAplicacionCopiadoras() {
       if (this.aplicacion == "Copiadoras") {
           return true;
       }
       return false;
    }
}

The .css file:

.colorCopiadoras {
    border-left: 1px solid #9fc4cb;
    color: #0d627a;
 }
.colorSolicitudes {
   border-left: 1px solid #989cbe;
   color: #6e43a9;
 }

When I remove the function, routerlinkactive works with the style, but when I include the function, it gives no error but does not paint the class


Solution

  • Wrap it in []

    import { Component, Input } from '@angular/core';
    import { Route, ActivatedRoute, Router, RouterLinkActive } from 
    '@angular/router';
    
    @Component({
      selector: 'app-sel',
      template: `
       <a [routerLink]="routeUrl" [routerLinkActive]="esAplicacionCopiadoras() ? 
      'colorCopiadoras' : 'colorSolicitudes'" ></a> `
      styleUrls: ['./submenu.component.css']
    })
    
    export class NavItemComponent {
       private aplicacion:bool =true;
         esAplicacionCopiadoras() {
           if (this.aplicacion == "Copiadoras") {
               return true;
           }
           return false;
        }
    }
    

    Attributes that are not wrapped in [] are evaluated as strings. You have to put attributes in [] in order to evaluate expressions.

    More information at Angular's website about template syntax