Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globally register a directive in Angular

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

like image 427
kamilkp Avatar asked Dec 21 '15 08:12

kamilkp


1 Answers

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.

like image 172
TGH Avatar answered Oct 10 '22 06:10

TGH