Angular - Using a component selector as an attribute makes tslint get angry
Asked Answered
T

2

12

I'm trying to create a component with an attribute as a selector, like this:

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

However, tslint is complaining about that, with the following message:

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

I know I could just disable that tslint rule, but I'd like to know if there's a reasonable reason why I shouldn't use an attribute as the component's selector before doing so.

Thanks in advance!

Tanah answered 7/2, 2018 at 11:20 Comment(0)
M
18

To allow linting for both element and attribute selectors, in tslint.config pass in an array ["element", "attribute"] instead of "element" or just "attribute":

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

As per reasons of taking the attribute approach, I will quote from this issue on codelyzer. Basically it's advisable when intending to just wrap low-level native input functionality like button or input without having to put a <my-custom-input> around them.

After listening to Angular Material team's talk in ng-conf about component API designs there is a case for using attribute selectors as components to allow components to be able to use the DOM API without needing to reflect 20+ bindings from the custom element style components to the inner DOM API it wraps.

Mazarin answered 25/9, 2018 at 21:57 Comment(0)
I
13

Your tslint.config file will be having this rule

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

Please modify that to allow attribute selector as below

"component-selector": [
  "attribute", 
  "myPrefix", 
  "camelCase"
]
Inion answered 7/2, 2018 at 11:30 Comment(3)
Hi @Aravind! Thanks for answering! As I said in my question, I know I could change/disable the rule in the tslint config file. However, what I was asking is if there is a reason why I shouldn't use an attribute as the component's selector.Tanah
Components are should be having element selectors and directives should be having attribute selectorsInion
yes I know but since Directives (as far as I know) can't have a template, I wanted to use an attribute as a selector so I can avoid extra tags like <my-selector><div>foo</div></my-selector>, which would break my css. That's why I wanted to know why using an attribute as the component's selector is not a "good practice" according to tslint. Anyway, I think I'm gonna just disable the rule for that line with /* tslint:disable-next-line */ for now (kinda dirty tho...).Tanah

© 2022 - 2024 — McMap. All rights reserved.