What exactly does a selector do in angular 2?

If we say in simple term selector is name which is used in our view like html tag. as we all know angular2 is component based. so selector is just provide the name of the component which is being called by its className in the directives list and called by selector name in the view of the another component like this:-

//suppose this is our component

@Component({
 selector : 'mycomponent'
 ....
})
export class Mycomponent{ }

now we can use this component in another component like this -

@Component({
 selector : 'secondcomponent',
 directives: [Mycomponent],  //here we use class name instead of selector name
 template: '<mycomponent></mycomponent>'  //here we used selector name
 ....
})
export class Mycomponent{ }

Also we can say selector is a complete functionality name used as html tag in the view.


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.

Tags:

Angular