Angular applications are built using components, which are the building blocks of the framework. A component in Angular controls a portion of the user interface and consists of a TypeScript class, an HTML template, and an optional CSS stylesheet. When building large applications, it’s common to divide the app into multiple components for better organization and reusability.
In this tutorial, we’ll create a simple Angular application with multiple components and demonstrate how to:
- Create new components.
- Use components in other components.
- Communicate between components using inputs and outputs.
Create Components
Use the Angular CLI to generate two components:
ng generate component header
ng generate component footer
This command creates the following structure for each component:
- A TypeScript file (
header.component.ts
orfooter.component.ts
) - An HTML file (
header.component.html
orfooter.component.html
) - A CSS file (
header.component.css
orfooter.component.css
) - A spec file for testing (e.g.,
header.component.spec.ts
) - Updates the
AppModule
by declaring the new components.
Modifying Component Templates
Header Component
Edit the header.component.html
file:
<header>
<h1>Welcome to My Angular App</h1>
</header>
Footer Component
Edit the footer.component.html
file:
<footer>
<p>© 2024 My Angular App</p>
</footer>
To include the HeaderComponent
and FooterComponent
in the main AppComponent
:
- Open
app.component.html
. - Add the selectors of the components:
<app-header></app-header>
<div class="content">
<p>Main content goes here.</p>
</div>
<app-footer></app-footer>
The app-header
and app-footer
tags correspond to the selector
property defined in header.component.ts
and footer.component.ts
.
Pingback: What Is Angular - Tech Mentor