繁体   English   中英

如何使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

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

在引入NgModule ,这个特征保持不变但变得不那么明显了。 正如在这个答案中所解释的那样,模块的适当层次结构是可能的。

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

如果某个单元未从模块导出,则只能在本地使用,而不能在同一模块中的其他单元中使用。

这个

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

将阻止is-right属性指令被编译到任何地方但是这个模块声明(即BreadcrumbsComponent )。

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

只有当元素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";
      ...
    }
  }

}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM