在 Angular 中全局注册一个指令 [英] Globally register a directive in Angular

查看:41
本文介绍了在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆