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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With