What does the selector do in this case?
import { Component } from '@angular/core'; import { HighlightDirective } from './highlight.directive'; @Component({ selector: 'my-app', templateUrl: 'app/app.component.html', directives: [HighlightDirective] }) export class AppComponent { }
And what does it do in this case?
@Directive({ selector: '[myHighlight]', host: { '(mouseenter)': 'onMouseEnter()', '(mouseleave)': 'onMouseLeave()' } })
Directives provide a powerful addition to the Angular platform giving us the ability to define behaviours on any element without the need to write a component. Each HTML DOM element can have zero or more directives attached, providing unlimited possibilities.
What is a selector? You have met selectors already. A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.
Every component is associated within an element that matches the component's selector. This element, into which the template is rendered, is called the host element. The :host pseudo-class selector may be used to create styles that target the host element itself, as opposed to targeting elements inside the host.
The component is applied to the <my-app></my-app>
tag in your index.html
. If your index.html
doesn't have that tag Angular will fail at startup. You can control where you Angular application will be played.
This is special for the Angular component that is created using bootstrap(AppComponent)
The directive selector [myHighlight]
will create aMyHighlight
directive instance for all elements that have a myHighlight
attribute like <xxx myHighlight>
and where MyHighLight
is listed in directives like
@Component({ selector: '...', directives: [MyHighlight], ... }) export class Xxx
Like the directive selector for other components (that are not the root component like AppComponent usually is), it works the same like the selector for the directive. The component has to be listed in the directives
array. Then all tags that match the selector are upgraded to Angular components.
Selectors are like CSS selectors. They can be attribute selectors, tag selectors, class selectors, id selectors and combinations of these. Also :not(...)
is supported.
What is not supported are selectors that need to match parent and child like with combinators like a b
or a > b
or a + b
where b is a sibling, child, descandant, ... of another component. A directive or component selector can always only refer to a single element.
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