Components are the main building blocks in Angular application, following are the features of Angular Components:
1. Angular Component comprises of Template File (component.html), CSS file (component.css) and Component class file (component.ts)
2. Angular component helps to execute logic written in component.ts file and render the html data written in template (component.html) file of component.
3. It can be used to pass data between other Components and services in Angular
4. We can create separate component for each new page to separate the code
5. We also can create separate Component for each sections of a page. e.g. Left menu Component, Header Component, Main-body Component, footer component.
After creating separate components, we can render it by calling selector of that particular component e.g. in our below example component selector is "app-employee", so by just calling "<app-employee></app-employee>" in any .html page we can render this component.
How to Create New Angular Component:
ng g c employee
ng is the Angular command and g stands for generate, c stands for component and after that we have to specify name of component to be created. Above command will create EmployeeComponent inside "src => app" folder as shown below.
Following is the code of EmployeeComponent, @Component decorator indicates it is Component class and it has selector of Component, using this selector we can call this employee component on other component page, templateUrl which tells name of html page of employee component and the styleUrls to indicate CSS class file of this component.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
Here it implements OnInit(), it calls ngOnInit() after constructor() when component is ready, we can add additional initialization in this ngOnInit() method, we also can skip this implementation if we want and we can remove ngOnInit() method from Component class if there is no such requirement.