Component Lifecycle
Angular components follow a structured lifecycle, consisting of several stages where specific actions can be performed. These stages are controlled by lifecycle hooks that developers can use to manage tasks such as initialization, change detection, and cleanup.
Here are the key lifecycle hooks:
- ngOnInit: This hook is called after Angular initializes the component's input properties and the component's view. It is commonly used to set up data or perform tasks that need to happen when the component loads.
- ngOnChanges: Triggered whenever the component's input properties change. It is useful for responding to updates in data that the component receives from a parent.
- ngOnDestroy: This hook is executed just before the component is removed from the DOM. It is ideal for cleaning up resources like subscriptions or event listeners to prevent memory leaks.
These lifecycle hooks allow developers to have fine-grained control over how components behave during their lifecycle.
Data Binding
Data binding in Angular is a mechanism that connects the component's data and the DOM, enabling seamless communication between the view and the component's logic. Angular provides four types of data binding:
Interpolation:
Syntax:
{{ expression }}
- Used to display component data within the view.
Example:
<p>{{ title }}</p>
Property Binding:
Syntax:
[property]="expression"
- Binds a DOM property to a component property.
Example:
<img [src]="imageUrl" />
Event Binding:
Syntax:
(event)="methodName()"
- Listens to user events like clicks and binds them to component methods.
Example:
<button (click)="handleClick()">Click Me</button>
Two-Way Binding:
Syntax:
[(ngModel)]="property"
Synchronizes the data between the component and the view in both directions.
Example:
<input [(ngModel)]="username" />
<p>{{ username }}</p>
By combining lifecycle hooks and data binding, Angular makes it easier to manage dynamic user interfaces and application logic, ensuring that the view and the component stay in sync.
Child Component
A child component is a component that is nested inside another component. It is useful for breaking down complex UIs into smaller, reusable parts. In the above example:
- The UserDetailsComponent acts as a child of the AppComponent.
- Data is passed from the parent to the child component using the @Input() decorator.
To further understand child components, here’s a simple use case where a parent component sends an array of users to a child component for display:
1. Modify the child component to handle an array:
@Input() users!: { name: string; age: number }[];
2. Update user-details.component.html to display the list:
<div *ngFor="let user of users">
<p>Name: {{ user.name }}, Age: {{ user.age }}</p>
</div>
3. Update the parent component:
users = [
{ name: 'Alice', age: 24 },
{ name: 'Bob', age: 27 }
];
4. Pass the array to the child component:
<app-user-details [users]="users"></app-user-details>
Creating a Component in Angular 8
A component in Angular is a TypeScript class with a decorator @Component. This decorator includes metadata such as the selector, template, and styles. Angular components make it easy to manage the UI and behavior of your application.
Steps to Create a Component
Install Angular CLI
Ensure you have the Angular CLI installed. You can install it using the following command:
npm install -g @angular/cli
Generate a Component
Use the CLI to create a component with the command:
ng generate component component-name
For example:
ng generate component user-profile
This command creates the following files in the src/app/user-profile/ directory:
- user-profile.component.ts (Logic)
- user-profile.component.html (Template)
- user-profile.component.css (Styles)
- user-profile.component.spec.ts (Test)
Structure of a Component
The primary file for a component is user-profile.component.ts. It looks like this:
import { Component } from '@angular/core';
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
userName: string = 'John Doe';
userAge: number = 25;
getUserInfo() {
return `Name: ${this.userName}, Age: ${this.userAge}`;
}
}
Editing the HTML Template
Modify the user-profile.component.html file to display the user’s information:
<div>
<h1>User Profile</h1>
<p>{{ getUserInfo() }}</p>
</div>
Adding Styles
Update the user-profile.component.css file to style the component:
h1 {
color: blue;
}
p {
font-size: 18px;
}
Using a Component in Angular 8
Once a component is created, it needs to be included in the Angular module and used in a parent component.
Steps to Use a Component
Add the Component to a Module
Open the app.module.ts file and ensure your component is declared:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { UserProfileComponent } from './user-profile/user-profile.component';
@NgModule({
declarations: [
AppComponent,
UserProfileComponent
],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Use the Component in HTML
The selector defined in the component decorator is used as a custom HTML tag.
Add the component to the app.component.html file:
<div>
<h1>Welcome to Angular App</h1>
<app-user-profile></app-user-profile>
</div>
Run the Application
Start the development server to view your component in action:
ng serve
Open the browser at http://localhost:4200. You’ll see:
Welcome to Angular App
User Profile
Name: John Doe, Age: 25
Implementation Code
Here’s a complete example of creating and using a component in Angular:
1. Component Class
import { Component } from '@angular/core';
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
userName: string = 'Alice';
userCity: string = 'New York';
getUserDetails() {
return `Name: ${this.userName}, City: ${this.userCity}`;
}
}
2. HTML Template
<div>
<h2>Profile Details</h2>
<p>{{ getUserDetails() }}</p>
</div>
3. Styles
h2 {
color: green;
}
p {
font-size: 16px;
font-family: Arial, sans-serif;
}
4. App Component
<div>
<h1>Angular Components Demo</h1>
<app-user-profile></app-user-profile>
</div>
Demo: Creating an Angular Component
Now that we understand what Angular components are, let’s create one from scratch. This step-by-step guide will help you build your first Angular component & understand how it works.
Step 1: Set Up Your Angular Project
Before creating a component, you need an Angular project. If you don’t have one, you can create it using the Angular CLI. Open your terminal & run the following command:
ng new my-first-app
This command creates a new Angular project named `my-first-app`. Navigate to the project folder:
cd my-first-app
Step 2: Generate a New Component
Angular CLI makes it easy to create components. To generate a new component, run the following command:
ng generate component my-first-component
This command creates a new folder named `my-first-component` inside the `src/app` directory. It also generates four files:
1. my-first-component.component.ts: The TypeScript file for the component.
2. my-first-component.component.html: The HTML template for the component.
3. my-first-component.component.css: The CSS file for styling the component.
4. my-first-component.component.spec.ts: A test file for the component.
Step 3: Understand the Generated Files
Let’s take a closer look at the `my-first-component.component.ts` file:
import { Component } from '@angular/core';
@Component({
selector: 'app-my-first-component',
templateUrl: './my-first-component.component.html',
styleUrls: ['./my-first-component.component.css']
})
export class MyFirstComponentComponent {
// Component logic goes here
}
- `selector: 'app-my-first-component'`: This is the custom HTML tag that Angular uses to include this component in other templates.
- `templateUrl: './my-first-component.component.html'`**: This points to the HTML file that defines the component’s view.
- `styleUrls: ['./my-first-component.component.css']`**: This links the CSS file for styling the component.
Step 4: Add Content to the Component
Open the `my-first-component.component.html` file & add some HTML:
<h2>Welcome to My First Component!</h2>
<p>This is a simple Angular component.</p>
You can also add some styles in the `my-first-component.component.css` file:
h2 {
color: blue;
}
p {
font-size: 18px;
}
Step 5: Use the Component in Your Application
To display this component, open the `app.component.html` file & add the component’s selector:
<app-my-first-component></app-my-first-component>
When you run your Angular application using the command `ng serve`, you will see the following output in your browser:
Welcome to My First Component!
This is a simple Angular component.
Step 6: Add Logic to the Component
You can also add logic to your component. For example, let’s add a property to the `MyFirstComponentComponent` class:
export class MyFirstComponentComponent {
message = 'This message is from the component class!';
}
Now, update the `my-first-component.component.html` file to display this message:
<h2>Welcome to My First Component!</h2>
<p>{{ message }}</p>
The double curly braces `{{ }}` are used to bind data from the component class to the template. When you run the application, you will see:
Welcome to My First Component!
This message is from the component class!
Frequently Asked Questions
What is the role of a selector in an Angular component?
The selector acts as a custom HTML tag to include the component in templates.
Can a component have multiple templates?
No, a component can only have one template, but you can use directives to conditionally render parts of it.
How do you share data between components?
Use Input and Output decorators to pass data and events between parent and child components.
Conclusion
Components are essential in Angular to build modular, maintainable, and reusable parts of your application. They separate logic, UI, and styles, making the development process organized and efficient. In this article, we covered how to create, use, and implement Angular Components Overview, complete with examples and code.