kamilkp kamilkp - 9 months ago 57
AngularJS Question

Globally register a directive in angular2

I am developing an Angular2 application. I need to add special behavior to all links so in angular 1.x i 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 angular2 i can write a directive like this:

selector: '[href]',

export class MyHrefDirective {
constructor() {
// whatever

But how on earth 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
array in every of those components (which is A LOT)?

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

Answer Source

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.