Components play a vital role in Angular applications as they serve as fundamental elements and essential features. They are responsible for rendering the UI of an application, handling user input, and communicating with other components.
A component is a class that has been decorated with the @Component decorator. This decorator provides the component with metadata, such as the selector, template, and style.
The selector is a string that is used to identify the component in the DOM. The template is the HTML code that is used to render the UI of the component. The style is the CSS code that is used to style the UI of the component.
Here's an instance of an Angular component.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
}
Create a component using the Angular CLI by running the below command
ng generate component <component-name>
Replace <component-name> with the name of your component.
Component Selectors
A selector is used to describe how the current component is rendered in the HTML DOM as well as to uniquely identify each component within the component tree.
The selector can be used primarily in three ways.
Selector as the Element Name
@Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], }) //use selector name directly inside angular //brackets like an html element <app-home></app-home>
Selector as an Attribute
@Component({ selector: '[app-home]', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], }) //use selector name as an attribute of any //html element <div app-home></div>
Selector as a Class
@Component({ selector: '.app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], }) //use selector name as a class of any //html element <div class="app-home"></div>