【问题标题】:The selector of the component "AppFooterComponent" should be used as element组件“AppFooterComponent”的选择器应用作元素
【发布时间】:2018-12-11 22:48:19
【问题描述】:

我的应用结构如下:

<body>
  <header>[...]</header>
  <main>[...]</main>
  <footer><app-footer></app-footer></footer>
</body>

由于我不想要不必要的 DOM 元素,我更喜欢将 app-footer 声明为属性,这样我就可以像这样声明页面:

<body>
  <header>[...]</header>
  <main>[...]</main>
  <footer app-footer></footer>
</body>

但如果我这样做了,我在执行ng lint时会收到以下错误消息

组件“AppFooterComponent”的选择器应用作元素(https://angular.io/styleguide#style-05-03

我认为这种情况是该规则的合法例外。你同意吗?如果是这样,我怎样才能将此特定组件声明为该规则的例外?

【问题讨论】:

    标签: angular tslint


    【解决方案1】:

    虽然这被认为是一种不好的做法(根据样式指南),但您仍然可以为此特定组件禁用此特定 ts lint 规则。

    为此,请在组件注释之前使用 /* tslint:disable:component-selector */ 以便组件声明如下所示:

    /* tslint:disable:component-selector */
    @Component({
        selector: '[app-footer]',
        templateUrl: './app-footer.component.html'
    })
    export class AppFooterComponent 
    

    【讨论】:

      【解决方案2】:

      当您定义 @Component 角度时,只允许将该组件用作 html 元素。如果您想将其用作元素的属性,请创建 @Directive

      import { Directive } from '@angular/core';
      
      @Directive({
        selector: '[app-footer]'
      })
      export class AppFooter { 
         .....
      }
      

      Doc

      【讨论】:

      • 但在这种情况下,我将无法定义页脚 html。你同意吗?
      • 你可以定义页脚元素。你不需要定义 app-footer 元素
      • 抱歉@SachilaRanarawaka 我不明白你的最后评论?如果您希望该元素的 html 像组件一样包含在它自己的 CSS 中怎么办?
      猜你喜欢
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 2019-09-27
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多