Angular routerLink [ng-reflect-router-link] styling not reflected in HTML in prod mode

3.1k views Asked by At

For a global solution in local/dev mode [ng-reflect-router-link] works in main.scss

[ng-reflect-router-link],  // [routerLink]
.pointer {
  cursor: pointer !important;
}

This doesn't work in production mode as [ng-reflect-router-link] is not emitted to the browser. Is there any known solution to still keep this global as we have many [routerLink]?

HTML (dev):

<div _ngcontent-bbw-c98="" class="value pointer" tabindex="0" ng-reflect-router-link="/whatever,1111">Name</div>

HTML (production):

<div _ngcontent-ryp-c98="" class="value" tabindex="0">Name</div>

Would like to apply on all [routerLink]s with default "cursor: pointer" styling. Any solutions?

1

There are 1 answers

3
Alex Biro On

The [ng-reflect-router-link] is kind of a side effect of the development mode, to help debug what directives were added in the template and what input params they had. They won't be there in production by design.

What you can do instead is write an attribute directive, but with the same selector as routerLink, inject the host element into that, and add a CSS class to it, eg. app-custom-link. Also, replace [ng-reflect-router-link] in the CSS selector with the class.

By hijacking the routerLink directive of @angular/router, you don't have to decorate all the links other than using the routerLink itself just as you would normally do, and you can add additional customisation with your own directive.

Examples

I created these based on the linked docs, but didn't run them, so there might be minor errors:

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[routerLink]'
})
export class CustomRouterLinkDirective {
    constructor(el: ElementRef) {
       el.nativeElement. classList.add('app-custom-link');
    }
}
.app-custom-link {
  cursor: pointer !important;
}

(You might be able to use your existing pointer class, but not sure what that does, so didn't want to mix it in.)

Usage

<span [routerLink]="['settings', 'profile']" >link text</span>

Caveats

Note, that if they change the attribute selector of the router (which they probably won't), you have to adjust your custom directive. Also note, that you probably can't really rely on which order the directives are executed, ie. your one and or the @angular/router one, so don't do stuff which conflicts with the router, eg. adjusting the href of the link.