Components in Angular 7
Components in angular basically are the key features for making the Angular Application. The complete application is built using the components. Simply puts, components is Typescript class Decorated with @Component which is the part of angular.
When we create a component in angular with the help of angular CLI four files are generated by default
1. .css file
2. .html file
3. .spec.ts file
4. .ts file
❖ The first file is used for giving the look and feel for the view.
❖ The second file is used for writing the HTML for the view
❖ The third file is used for the unit testing for a particular component
❖ The fourth file is used writing the main business login in Typescript
When we create an angular project then one component is automatically generated by the default app component which is the root component of an angular application. The root app component has the following files-
app.component.html
app.component.spec.ts
app.component.ts
app.module.ts
And if you select the routing option during the project setup then one more file also generated for handling the routing
App-routing.module.ts
Angular CLI has one command for creating the component. However, the app component generated default during the project setup is the parent component and remaining all the components created manually are the child component
Command for generating the component-
ng generate component component_name
OR ng g c component_name
Example:-
Now run the command to create the component with the below line of code-
ng g c demo-cmp
When you run the above command in the command line, you will get the following result-
❖ CREATE src/app/demo-cmp/demo-cmp.component.html
❖ CREATE src/app/demo-cmp/demo-cmp.component.spec.ts
❖ CREATE src/app/demo-cmp/demo-cmp.component.ts
❖ CREATE src/app/demo-cmp/demo-cmp.component.css
❖ UPDATE src/app/app.module.ts
Let us check file structure in demo-cmp ->
1- demo-cmp.component.ts
import { Component, OnInit } from '@angular/core';
@Component
(
{
selector: 'app-demo-cmp', templateUrl: './demo-cmp.component.html', styleUrls: ['./demo-cmp.component.css']
}
)
export class DemoCmpComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
}
-A component selector is a css selector that tells how angular finds this particular component in html page
- templateUrl is path or url of a template file for an angular component
- StyleUrls one or more path or url for files containing css to use in this component
- Inside the @component decorator, we can use template instead of templateUrl and style instead of styleUrls
- A template is an inline html for an angular component
style is an inline css
2 - demo-cmp.component.html
<p> demo-cpm works!
</p>