Angular - 2-9 Fully understand the component selector

We have learned a lot about components, templates and the options the framework gives us to declare styles. Let's now focus on the last property of the @Component decorator we still need to explore: the selector. We already mentioned that it must be unique so that you do not accidentally override an existing element, possibly even a component shipped by another package you depend on. But there is also another important detail about the selector worth knowing.

You are not forced to use a selector that targets a custom element. The default selector behaves exactly like a CSS selector. When you write selector: 'app-servers', Angular treats it like the H3 selector in CSS: any <app-servers></app-servers> in your templates will be replaced by the component. Because it follows CSS rules, you are not limited to element selectors. You can also target an attribute by wrapping the name in brackets: selector: '[app-servers]'. If you do this, the original element selector stops working: Angular will throw "app-servers is not a known element". You then need to replace the custom element by a regular HTML element decorated with the app-servers attribute, for example <div app-servers></div>.

The three valid selector forms

  • Element selector (default): selector: 'app-servers'
  • Attribute selector: selector: '[app-servers]'
  • Class selector: selector: '.app-servers'

Selecting by id (#id) or by pseudo-class such as :hover is not supported by Angular. In practice, for components we almost always stick with the element selector because we create our own tags. The attribute and class forms come into play when we will discover directives, a related but distinct feature. It is still useful to know that the selector accepts these CSS-style variants, because some use cases - especially when you want to enhance an existing element rather than introduce a brand new one - benefit from a different selector strategy.