在Angular中全局注册指令 [英] Globally register a directive in Angular
问题描述
我正在开发Angular应用程序.我需要向所有链接添加特殊行为.在AngularJS中,只需编写如下指令:
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
}
};
});
在Angular中,我可以编写如下指令:
In Angular I can write a directive like this:
@Directive({
selector: '[href]',
})
export class MyHrefDirective {
constructor() {
// whatever
}
}
但是如何告诉应用程序全局使用该指令?我有很多观点,并附有链接.我是否必须将其导入并在所有这些组件(很多)的directives
数组中指定它?
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)?
我尝试将其注入到bootstrap
函数中,就像您应该在服务中那样在全局具有一个实例,但无效
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
推荐答案
我的理解是,您必须在组件级别选择加入所有自定义指令.仅包含PLATFORM_DIRECTIVES(ngFor,ngIf等).
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.).
但是,您可以将自己的自定义指令注册为PLATFORM_DIRECTIVE
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}),
]);
这里是一篇文章,详细介绍了该过程: http://blog.thoughtram. io/angular2/2015/11/23/multi-providers-in-angular-2.html
Here is an article that talks more about the process: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html
由于组件是在模块级别声明的,所以我现在认为这不再是一个问题.这意味着更少的重复,因为您不再需要在单个组件级别声明子组件.
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.
这篇关于在Angular中全局注册指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!