Different types of Component Selectors in 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 element or component available by a number of third-party packages.

There are mainly three ways to use the selector in HTML:

  1. 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.

For any other query visit Angular Documentation

Knoldus-blog-footer-image

Written by 

Rudar Daman Singla is the Trainee Software Consultant at Knoldus Software LLP. He has done B.Tech. from Jaypee University of Information technology, Waknaghat(Solan). He has good knowledge of languages C, C++, Java, Scala, HTML, CSS, PHP, Node and Angular. He is also interested in VFX. As a fresher, he always tries to explore the different type of software and tools.

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!