Before talking about Component Selector in Angular, let’s figure out – What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.
Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components. Angular components are a subset of directives, always associated with a template. Unlike other directives, only one component can be instantiated per element in a template.
There are a lot of properties present inside a component decorator. In this blog, I will focus on the selector property. The selector is a property inside the angular component which identifies the directive in a template and triggers instantiation of the directive. The selector has to be unique so that it doesn’t override already existing elements or components available by a number of third-party packages.
There are mainly three ways to use the selector in HTML:
- Selector can directly be used by typing element-name directly as a legacy selector:
@Component({
selector: 'app-element',
template: './element.component.html',
styleUrls: ['./element.component.css']
})
This type of selector can access directly by typing the selector name inside the <> brackets as:
<app-element></app-element>
2. The selector can be used as attribute selector by put the selector into square brackets:
@Component({
selector: '[app-element]',
template: './element.component.html',
styleUrls: ['./element.component.css']
})
In this, we have changed our selector to be an attribute. To access this type of attribute selector we have to put this as an attribute inside a div or any other element as:
<div app-element></div>
3. The selector can also be select by class just like in CSS by putting a dot in the beginning:
@Component({
selector: '.app-element',
template: './element.component.html',
styleUrls: ['./element.component.css']
})
In this, we can select by class as:
<div class="app-element"></div>
Note: Selecting by ID and by all pseudo selectors such as hover and so on won’t work as they are not supported by Angular.
Would you like to explore Data Bindings in Components? Data binding is the communication between the typescript code and the HTML code of a component. Explore More Here >>
For any other query visit Angular Documentation