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!
The usage of attribute selectors is not limited to directives only, since you can use them as selectors for Angular components as well. Sometimes it’s the only possibility as with the table row example, whereas it’s an option for scenarios such as presented in the second case.
Then go inside the ComponentSelectorDemo folder and create three components using Angular CLI commands: These three components represent the three selectors of a component namely element selector, attribute selector, and class selector. Now let's add some code and markup to these components and see them in action.
But, there is a shorter way available for the above in Angular. You can use the Attribute parameter decorator to pass the value of the HTML attribute to the component or directive constructor through dependency injection. So for an earlier example, to read the type attribute, we will do something like below:
A CSS element selector is by far the most popular way to mark an Angular component. Although, an attribute selector is mainly meant to be used for Angular directives, you can use it as a component selector as well.
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.
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"
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With