I come from a HTML CSS Javascript background and I just started learning Angular with their official tutorial "Tour of Heroes".
I noticed that the official tutorial and other Youtubers whose videos I have been watching, refer to the selector of the component as CSS Selector. I do not understand why CSS is being included in the term here.
As far as I have understood, selector of a component looks for a matching tag on the root/parent component and it is a html tag in a html page.
Unable to understand how CSS comes into the picture for the term to be a CSS Selector
@Component({
selector: 'app-heroes', //This is what I am referring to.
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.scss', './test.scss']
})
A selector in CSS defines a rule on how to match against the DOM, determining where / when a given style rule applies. In Angular, directive / component selectors use these very selectors, too, to define what elements they apply to. Element selectors (like "app-my-component"
) for components are what you'll see most of the time, but you're not limited to those.
For example, you could write a component with a selector of "a[href]"
which matches any a
element that also has an href
attribute. In fact, you could even use a selector of "[href]"
, matching on any element with such an attribute. You could even use a selector like ":not([href])"
to apply your directive on any element which does not have such an attribute.
In practice this can be quite useful, especially for directives. In fact, if you look at the source code of Angular's RouterLink directive, you'll find that it is actually implemented as two separate directives, one with a selector of a[routerLink]
and one with a selector of :not(a)[routerLink]
.