【问题标题】:Angular - Using a component selector as an attribute makes tslint get angryAngular - 使用组件选择器作为属性会使 tslint 生气
【发布时间】:2018-07-17 16:01:20
【问题描述】:

我正在尝试创建一个带有属性作为选择器的组件,如下所示:

@Component({
    selector: '[my-attribute-selector]',
    template: ``
})
export class MyComponent { 
   // Some cool stuff
}

但是,tslint 对此进行了抱怨,并带有以下消息:

[tslint] The selector of the component "MyComponent" should be used as element

我知道我可以禁用该 tslint 规则,但我想知道在这样做之前是否有合理的理由不应该使用属性作为组件的选择器。

提前致谢!

【问题讨论】:

    标签: angular tslint


    【解决方案1】:

    要允许 元素和属性选择器进行 linting,请在 tslint.config 中传入数组 ["element", "attribute"] 而不是 "element" 或只是 "attribute"

    "component-selector": [
            true,
            ["element", "attribute"],
            "app",
            "kebab-case"
        ]
    

    根据采用属性方法的原因,我将引用this issue on codelyzer。基本上,当打算只包装低级本机输入功能(如 buttoninput 而不必在它们周围放置 <my-custom-input> 时)是可取的。

    听完Angular Material team's talk in ng-conf about component API designs 有一个案例是使用属性选择器作为 components 以允许组件能够使用 DOM API,而无需 需要从自定义元素样式中反映 20 多个绑定 组件到它包装的内部 DOM API。

    【讨论】:

      【解决方案2】:

      您的tslint.config 文件将具有此规则

      "component-selector": [
        "element",
        "app",
        "kebab-case"
      ],
      

      请修改它以允许attribute 选择器如下

      "component-selector": [
        "attribute", 
        "myPrefix", 
        "camelCase"
      ]
      

      【讨论】:

      • 嗨@Aravind!谢谢回答!正如我在问题中所说,我知道我可以更改/禁用 tslint 配置文件中的规则。但是,我要问的是我是否有理由不使用属性作为组件的选择器。
      • 组件应该有元素选择器,指令应该有属性选择器
      • 是的,我知道,但由于指令(据我所知)没有模板,我想使用属性作为选择器,这样我就可以避免像<my-selector><div>foo</div></my-selector> 这样的额外标签,这将打破我的CSS。这就是为什么我想知道为什么根据 tslint 使用属性作为组件的选择器不是一个“好习惯”。无论如何,我想我现在要用/* tslint:disable-next-line */ 禁用该行的规则(有点脏...)。
      猜你喜欢
      • 2018-12-25
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2017-03-16
      • 2020-05-27
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      相关资源
      最近更新 更多