Globally register a directive in Angular

All we need is an easy explanation of the problem, so here it is.

I am developing an Angular application. I need to add special behavior to all links. In AngularJS would just write a directive like this:

angular.module('whatever.module', []).directive('href', function() {
    return {
        restrict: 'A',
        link: function($scope, $element, $attrs) {
            // do stuff
        }
    };
});

In Angular I can write a directive like this:

@Directive({
    selector: '[href]',
})

export class MyHrefDirective {
    constructor() {
        // whatever
    }
}

But how can I tell the application to use that directive globally? I have a ton of views with links on them. Do I have to import it and specify it in the directives array in every of those components (which is A LOT)?

I tried injecting it to the bootstrap function like you’re supposed to do with services to have one instance globally but that didn’t work

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

My understanding is that you have to opt in to all custom directives at the component level. Only PLATFORM_DIRECTIVES are implicitly included (ngFor, ngIf etc.).

However, you can register your own custom directive as a PLATFORM_DIRECTIVE

import { provide, PLATFORM_DIRECTIVES } from '@angular/core';

bootstrap(RootCmp, [
  provide(PLATFORM_DIRECTIVES, {useValue: YourCustomDirective, multi: true}),
]);

Here is an article that talks more about the process:
http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html

EDIT:
I consider this less of a concern now since components are declared at the module level. This means a lot less repetition since you no longer have to declare child components at the individual component level.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply