What is a Component?A component in Angular is a fundamental building block of the application. It represents a reusable piece of the user interface (UI) that combines:
Generating a Component with CLIAngular CLI simplifies component creation. To generate a component named User in a components folder, use:This command creates:
Component Metadata (
Component StructureA component typically consists of three files:
Interpolation {{ }} and Property Binding
Event Binding ((event))Event binding listens for user actions (e.g., clicks) and calls component methods using (event)="method()".Example:
Two-Way Data Binding ([(ngModel)])Two-way data binding synchronizes data between the component and the template. It requires the FormsModule.Example:
Lifecycle HooksLifecycle hooks are methods Angular calls at specific points in a component’s lifecycle. Common hooks include:
Hands-on Project: Create User & Admin ComponentsLet’s create a simple Angular project with two components: UserComponent and AdminComponent. Each will have a form and log lifecycle events.Step 1: Set Up the ProjectStep 3: Implement AdminComponentThis component will have a form to capture an admin’s role and log lifecycle events.Step 4: Run the Application
Summary
- HTML template: Defines the view or UI structure.
- TypeScript class: Handles the logic and data.
- CSS styles: Defines the component’s appearance.
- Metadata: Configures how the component behaves (via the @Component decorator).
Generating a Component with CLIAngular CLI simplifies component creation. To generate a component named User in a components folder, use:
bash
ng g component components/user
- user.component.ts (TypeScript logic)
- user.component.html (HTML template)
- user.component.css (Styles)
- user.component.spec.ts (Test file)
Component Metadata (
@Component
Decorator)The @Component decorator defines metadata for the component, telling Angular how to process it. Key properties include:- selector: The custom HTML tag to use the component (e.g., <app-user>).
- templateUrl: Path to the component’s HTML template file.
- styleUrls: Array of paths to CSS files for styling.
- standalone: If true, the component doesn’t belong to an NgModule (new in Angular 14+).
typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
standalone: true
})
export class UserComponent {
// Component logic here
}
- selector: Use <app-user></app-user> in parent templates to render this component.
- templateUrl: Points to user.component.html for the UI.
- styleUrls: Points to user.component.css for styles.
- standalone: true: Indicates this component is self-contained and doesn’t require an NgModule.
Component StructureA component typically consists of three files:
- .ts (TypeScript): Contains the component class, logic, and lifecycle hooks.
- .html: Defines the UI template.
- .css: Contains styles specific to the component.
src/app/components/user/
├── user.component.ts
├── user.component.html
├── user.component.css
Interpolation {{ }} and Property Binding
- Interpolation: Displays component data in the template using {{ variable }}.
- Property Binding: Binds a component property to an HTML element property using [property]="value".
typescript
// user.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
standalone: true
})
export class UserComponent {
name = 'John Doe';
}
html
<!-- user.component.html -->
<p>Hello, {{ name }}!</p>
<input [value]="name" />
- {{ name }} displays the name property’s value.
- [value]="name" binds the name property to the input’s value attribute.
Event Binding ((event))Event binding listens for user actions (e.g., clicks) and calls component methods using (event)="method()".Example:
typescript
// user.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
standalone: true
})
export class UserComponent {
message = '';
onClick() {
this.message = 'Button clicked!';
}
}
html
<!-- user.component.html -->
<button (click)="onClick()">Click Me</button>
<p>{{ message }}</p>
- (click)="onClick()" calls the onClick method when the button is clicked.
Two-Way Data Binding ([(ngModel)])Two-way data binding synchronizes data between the component and the template. It requires the FormsModule.Example:
typescript
// user.component.ts
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
standalone: true,
imports: [FormsModule] // Import FormsModule for ngModel
})
export class UserComponent {
username = 'John';
}
html
<!-- user.component.html -->
<input [(ngModel)]="username" />
<p>You typed: {{ username }}</p>
- [(ngModel)] binds the input value to the username property, updating both on change.
- FormsModule must be imported for ngModel to work.
Lifecycle HooksLifecycle hooks are methods Angular calls at specific points in a component’s lifecycle. Common hooks include:
- ngOnInit: Called once after the component is initialized.
- ngOnDestroy: Called before the component is destroyed.
typescript
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
standalone: true
})
export class UserComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('UserComponent initialized');
}
ngOnDestroy() {
console.log('UserComponent destroyed');
}
}
- ngOnInit is ideal for initialization tasks (e.g., fetching data).
- ngOnDestroy is used for cleanup (e.g., unsubscribing from observables).
Hands-on Project: Create User & Admin ComponentsLet’s create a simple Angular project with two components: UserComponent and AdminComponent. Each will have a form and log lifecycle events.Step 1: Set Up the Project
- Install Angular CLI (if not installed):bash
npm install -g @angular/cli
- Create a new Angular project:bash
ng new angular-components-demo cd angular-components-demo
- Generate the components:bash
ng g component components/user ng g component components/admin
- Configure the app.component.html to include both components:html
<!-- src/app/app.component.html --> <app-user></app-user> <app-admin></app-admin>
- Ensure app.component.ts is standalone (Angular 20 defaults to standalone components):typescript
// src/app/app.component.ts import { Component } from '@angular/core'; import { UserComponent } from './components/user/user.component'; import { AdminComponent } from './components/admin/admin.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', standalone: true, imports: [UserComponent, AdminComponent] }) export class AppComponent {}
typescript
// src/app/components/user/user.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
standalone: true,
imports: [FormsModule]
})
export class UserComponent implements OnInit, OnDestroy {
user = { name: '', email: '' };
ngOnInit() {
console.log('UserComponent: Initialized');
}
ngOnDestroy() {
console.log('UserComponent: Destroyed');
}
onSubmit() {
console.log('User Form Submitted:', this.user);
}
}
html
<!-- src/app/components/user/user.component.html -->
<h2>User Form</h2>
<form (ngSubmit)="onSubmit()">
<label>Name: </label>
<input [(ngModel)]="user.name" name="name" placeholder="Enter name" />
<br /><br />
<label>Email: </label>
<input [(ngModel)]="user.email" name="email" placeholder="Enter email" />
<br /><br />
<button type="submit">Submit</button>
</form>
<p>User: {{ user.name }} | Email: {{ user.email }}</p>
css
/* src/app/components/user/user.component.css */
form {
margin: 20px;
padding: 20px;
border: 1px solid #ccc;
}
input {
padding: 5px;
margin: 5px;
}
typescript
// src/app/components/admin/admin.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css'],
standalone: true,
imports: [FormsModule]
})
export class AdminComponent implements OnInit, OnDestroy {
admin = { role: '' };
ngOnInit() {
console.log('AdminComponent: Initialized');
}
ngOnDestroy() {
console.log('AdminComponent: Destroyed');
}
onSubmit() {
console.log('Admin Form Submitted:', this.admin);
}
}
html
<!-- src/app/components/admin/admin.component.html -->
<h2>Admin Form</h2>
<form (ngSubmit)="onSubmit()">
<label>Role: </label>
<input [(ngModel)]="admin.role" name="role" placeholder="Enter role" />
<br /><br />
<button type="submit">Submit</button>
</form>
<p>Admin Role: {{ admin.role }}</p>
css
/* src/app/components/admin/admin.component.css */
form {
margin: 20px;
padding: 20px;
border: 1px solid #007bff;
}
input {
padding: 5px;
margin: 5px;
}
- Start the Angular development server:bash
ng serve
- Open your browser and navigate to http://localhost:4200.
- You should see:
- A User Form with fields for name and email.
- An Admin Form with a field for role.
- Open the browser’s console (F12) to see lifecycle logs (ngOnInit when components load, ngOnDestroy if you navigate away or destroy the component).
- Test the forms:
- Enter data in the User and Admin forms.
- Submit the forms to see the console logs with form data.
html
<!-- src/app/app.component.html -->
<button (click)="showUser = !showUser">Toggle User Component</button>
<button (click)="showAdmin = !showAdmin">Toggle Admin Component</button>
<app-user *ngIf="showUser"></app-user>
<app-admin *ngIf="showAdmin"></app-admin>
typescript
// src/app/app.component.ts
import { Component } from '@angular/core';
import { UserComponent } from './components/user/user.component';
import { AdminComponent } from './components/admin/admin.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
standalone: true,
imports: [UserComponent, AdminComponent]
})
export class AppComponent {
showUser = true;
showAdmin = true;
}
- Click the toggle buttons to add/remove components.
- Check the console for ngOnInit (when added) and ngOnDestroy (when removed).
Summary
- Components: Building blocks of Angular apps, combining logic, template, and styles.
- CLI: Use ng g component to generate components.
- Metadata: @Component defines selector, templateUrl, styleUrls, and standalone.
- Data Binding:
- Interpolation ({{ }}): Display data.
- Property Binding ([]): Bind data to properties.
- Event Binding (()): Handle user events.
- Two-Way Binding ([(ngModel)]): Sync data with FormsModule.
- Lifecycle Hooks: Use ngOnInit for initialization and ngOnDestroy for cleanup.
- Project: You created User and Admin components with forms and lifecycle logging.
0 comments:
Post a Comment