The main job of Angular Components and Templates
Categories: Angular JS Angular
The main job of Angular Components and Templates
Components are building block of Angular application. The main job of Angular Component is to generate a section of web page called view. Every component will have an associated template and it will be used to generate views.
Add a component
Let us create a new component in our ExpenseManager application.
Open command prompt and go to ExpenseManager application.
cd /go/to/expense-manager
Create a new component using ng generate component command as specified below:
ng generate component expense-entry
Output
The output is mentioned below:
CREATE src/app/expense-entry/expense-entry.component.html (28 bytes)
CREATE src/app/expense-entry/expense-entry.component.spec.ts (671 bytes)
CREATE src/app/expense-entry/expense-entry.component.ts (296 bytes)
CREATE src/app/expense-entry/expense-entry.component.css (0 bytes)
UPDATE src/app/app.module.ts (431 bytes)
Here,
- ExpenseEntryComponent is created under src/app/expense-entry folder.
- Component class, Template and stylesheet are created.
- AppModule is updated with new component.
Add title property to ExpenseEntryComponent (src/app/expense-entry/expenseentry.component.ts) component.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-expense-entry',
templateUrl: './expense-entry.component.html',
styleUrls: ['./expense-entry.component.css']
})
export class ExpenseEntryComponent implements OnInit {
title: string;
constructor() { }
ngOnInit() {
this.title = "Expense Entry"
}
}
Update template, src/app/expense-entry/expense-entry.component.html with
below content.
<p>{{ title }}</p>
Open src/app/app.component.html and include newly created component.
<h1>{{ title }}</h1>
<app-expense-entry></app-expense-entry>
Here,
app-expense-entry is the selector value and it can be used as regular HTML Tag.