如何使 Angular 指令只能由一个组件使用?

How do I make an Angular directive usable only by one component?

我知道能够使用我的指令的唯一方法是在模块中导出它。

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [BreadcrumbsComponent, IsRightDirective],
  exports: [BreadcrumbsComponent, IsRightDirective]
})
export class BreadcrumbsModule { }

我的 BreadcrumbsModule 是由我的 AppModule 导入的

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BreadcrumbsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

现在,当我使用我的面包屑组件时,我将其命名为选择器 bulma-breadcrumbs,并添加属性 is-right,它按预期工作。但是,如果我将它添加到另一个标签,如 h1,该指令也会影响它。

我正在尝试让指令仅适用于 BreadcrumbsComponent

仅当元素 tagNamebulma-breadcrumbs:

时才能使指令生效
export class IsRightDirective {

  constructor(private elementRef: ElementRef) {
    let element = elementRef.nativeElement as HTMLElement;
    if (element.tagName.toLowerCase() === "bulma-breadcrumbs") {
      element.style.border = "solid 4px red";
      ...
    }
  }

}

有关代码的工作示例,请参阅 this stackblitz

在 Angular 2 RC5 之前,directives/components 的层次结构是透明的,因为组件具有 directives 属性 定义的 components/directives 仅影响此组件及其子项。

引入NgModule后,此功能仍然完好无损,但变得不那么明显了。如 中所述,使用适当的模块层次结构是可能的。

大多数时候模块 declarationsexports 相同,这允许在应用程序中全局使用模块指令、组件和管道。

如果一个单元不是从模块中导出的,那么它只能在本地使用,对同一模块中的其他单元可用。

这个

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [BreadcrumbsComponent, IsRightDirective],
  exports: [BreadcrumbsComponent]
})
export class BreadcrumbsModule { }

将阻止 is-right 属性指令在除此模块声明(即 BreadcrumbsComponent)之外的任何地方编译。

或者,指令 selector 可以限制为 bulma-breadcrumbs[is-right]。结果将相同,但这不会阻止该指令在具有本地 bulma-breadcrumbs 组件的其他模块中使用。