20
Various Types of Angular Component Selectors
Today we will be learning the various ways of using the component selector in Angular.
If you are unaware of what is a component in Angular or what are the different parts of it I would recommend you to have a quick read on the following article - Understanding-Components.
There are mainly four different ways you can define a selector in Angular component.
i. Tag Selector
When a component is created by default it is provided with a tag selector.
app.component.ts file
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'MyFirstProject';
}
Lets use the selector in our index.html file in the following way-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>MyFirstProject</title>
<base href="/" />
<meta name="viewport" content="width=device-width,
initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
</body>
</html>
ii. Class Selector
The class selector syntax is similar to the CSS class .
import { Component } from '@angular/core';
@Component({
selector: '.app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'MyFirstProject';
}
In the index file we can use the selector in the below way
<body>
<div class="app-root"></div>
</body>
iii. ID Selector
The id selector syntax also resemble like the CSS id selector.
import { Component } from '@angular/core';
@Component({
selector: '#app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'MyFirstProject';
}
In the index.html file lets see how the selector has been used.
<body>
<div id="app-root"></div>
</body>
iv. Attribute Selector
The attribute selector syntax in the component decorator selector metadata looks like [app-name]
import { Component } from '@angular/core';
@Component({
selector: '[app-root]',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'MyFirstProject';
}
In the index.html it will be used as any other attribute inside a html element.
<div app-root></div>
So now we completed learning the different ways we can write and use the selectors in Angular.
Hope you enjoyed the post, if you enjoyed it do like and comment.
Also if you want any specific topic please write it in the comment section.
Coming up next some more advanced features on Angular Component and more Angular topics. So stay tuned.
Cheers!!!
Happy Coding
20