In this section, we will delve into the core building blocks of any Angular application: components. Components are the fundamental units of an Angular application, encapsulating the logic, template, and styles that define a part of the user interface.
Key Concepts
- Component Definition: A component in Angular is defined using a TypeScript class decorated with
@Component
. - Component Metadata: The
@Component
decorator provides metadata about the component, such as its selector, template, and styles. - Component Lifecycle: Components have a lifecycle managed by Angular, with hooks that allow you to tap into key moments of a component's existence.
Creating a Component
Step-by-Step Guide
-
Generate a Component: Use Angular CLI to generate a new component.
ng generate component my-component
This command creates a new folder named
my-component
with the following files:my-component.component.ts
: The TypeScript file containing the component class.my-component.component.html
: The HTML template for the component.my-component.component.css
: The CSS styles for the component.my-component.component.spec.ts
: The test file for the component.
-
Component Class: The generated
my-component.component.ts
file will look like this:import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponent implements OnInit { constructor() { } ngOnInit(): void { } }
@Component
: Decorator that marks the class as an Angular component and provides metadata.selector
: The HTML tag that represents the component.templateUrl
: Path to the HTML template file.styleUrls
: Path to the CSS file(s).
-
Template: The
my-component.component.html
file contains the HTML structure of the component.<p> my-component works! </p>
-
Styles: The
my-component.component.css
file contains the styles specific to the component.p { color: blue; }
Practical Example
Let's create a simple component that displays a list of items.
-
Generate the Component:
ng generate component item-list
-
Modify the Component Class (
item-list.component.ts
):import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-item-list', templateUrl: './item-list.component.html', styleUrls: ['./item-list.component.css'] }) export class ItemListComponent implements OnInit { items: string[] = ['Item 1', 'Item 2', 'Item 3']; constructor() { } ngOnInit(): void { } }
-
Update the Template (
item-list.component.html
):<ul> <li *ngFor="let item of items">{{ item }}</li> </ul>
-
Add Some Styles (
item-list.component.css
):ul { list-style-type: none; padding: 0; } li { background-color: #f0f0f0; margin: 5px 0; padding: 10px; border-radius: 4px; }
Using the Component
To use the ItemListComponent
in your application, include its selector in the template of another component, such as app.component.html
:
Practical Exercises
Exercise 1: Create a User Profile Component
- Generate a new component named
user-profile
. - Add properties for
name
,age
, andemail
in the component class. - Display these properties in the component template.
- Style the template to make it visually appealing.
Solution:
-
Generate the component:
ng generate component user-profile
-
Update the component class (
user-profile.component.ts
):import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-user-profile', templateUrl: './user-profile.component.html', styleUrls: ['./user-profile.component.css'] }) export class UserProfileComponent implements OnInit { name: string = 'John Doe'; age: number = 30; email: string = '[email protected]'; constructor() { } ngOnInit(): void { } }
-
Update the template (
user-profile.component.html
):<div class="profile"> <h2>{{ name }}</h2> <p>Age: {{ age }}</p> <p>Email: {{ email }}</p> </div>
-
Add styles (
user-profile.component.css
):.profile { border: 1px solid #ccc; padding: 20px; border-radius: 8px; max-width: 300px; margin: 20px auto; text-align: center; } h2 { margin-bottom: 10px; } p { margin: 5px 0; }
Common Mistakes and Tips
- Selector Naming: Ensure the selector name is unique to avoid conflicts with other components.
- Template and Style Paths: Verify that the paths to the template and style files are correct.
- Lifecycle Hooks: Utilize lifecycle hooks like
ngOnInit
to perform initialization logic.
Conclusion
In this section, we learned how to create and use components in Angular. We covered the basics of component definition, metadata, and lifecycle. We also walked through a practical example and provided an exercise to reinforce the concepts. In the next section, we will explore component templates in more detail.
Angular 2+ Course
Module 1: Introduction to Angular
Module 2: TypeScript Basics
- Introduction to TypeScript
- TypeScript Variables and Data Types
- Functions and Arrow Functions
- Classes and Interfaces