Components and Templates
40 minComponents are the fundamental building blocks of Angular applications, encapsulating template (view), styles, and logic (component class) into reusable units. Each component represents a part of the user interface and can be composed with other components to build complex applications. Components use the `@Component` decorator to define metadata like selector, template, and styles. Understanding components is essential for Angular development, as everything in Angular is built around components.
Templates define the view (HTML) that users see. Angular templates use special syntax beyond standard HTML: interpolation (`{{ }}`) for displaying data, property binding (`[property]="value"`) for setting element properties, event binding (`(event)="handler()"`) for handling user interactions, and two-way binding (`[(ngModel)]`) for form inputs. Templates also support structural directives like `*ngIf` (conditional rendering), `*ngFor` (looping), and `*ngSwitch` (multiple conditions). Understanding template syntax is crucial for building dynamic, interactive UIs.
Data binding connects component class properties to template elements, enabling dynamic content. Interpolation displays component data in the template. Property binding sets element properties, attributes, and component inputs. Event binding listens to DOM events and calls component methods. Two-way binding combines property and event binding for form inputs. Angular's change detection automatically updates the view when component data changes. Understanding data binding enables you to create reactive, data-driven interfaces.
Component classes contain the logic and data for components. They're TypeScript classes decorated with `@Component`. Component classes define properties (data), methods (behavior), and lifecycle hooks (ngOnInit, ngOnDestroy, etc.). Components can receive data through `@Input()` properties and emit events through `@Output()` properties. Understanding component classes and their lifecycle helps you manage component state, handle initialization, and clean up resources properly.
Component communication enables components to share data and coordinate behavior. Parent-to-child communication uses `@Input()` properties. Child-to-parent communication uses `@Output()` EventEmitters. Sibling components can communicate through shared services or parent components. Understanding component communication patterns helps you design component hierarchies and build maintainable applications. Components should be focused, reusable, and loosely coupled.
Best practices include keeping components focused on a single responsibility, using OnPush change detection for better performance, extracting reusable logic into services, using component lifecycle hooks appropriately, and following Angular style guide conventions. Components should be testable, maintainable, and follow the single responsibility principle. Understanding components and templates is the foundation of Angular development.
Key Concepts
- Components are the building blocks of Angular applications.
- Templates use Angular syntax (interpolation, binding, directives).
- Data binding connects component data to template views.
- Component classes contain logic, properties, and lifecycle hooks.
- Components communicate through @Input() and @Output() properties.
Learning Objectives
Master
- Creating Angular components with templates and styles
- Using Angular template syntax (interpolation, binding, directives)
- Implementing data binding between components and templates
- Understanding component lifecycle and communication
Develop
- Component-based architecture thinking
- Understanding reactive, data-driven UI development
- Designing reusable, maintainable components
Tips
- Use interpolation {{ }} for displaying component data in templates.
- Use property binding [property] for setting element properties dynamically.
- Use event binding (event) for handling user interactions.
- Use *ngIf and *ngFor for conditional rendering and looping.
Common Pitfalls
- Forgetting to import FormsModule for two-way binding with ngModel.
- Not understanding change detection, causing performance issues.
- Creating components that are too large, violating single responsibility.
- Not using @Input() and @Output() properly for component communication.
Summary
- Components encapsulate template, styles, and logic into reusable units.
- Templates use Angular syntax for dynamic, interactive views.
- Data binding connects component data to template elements.
- Component classes contain logic, properties, and lifecycle hooks.
- Understanding components and templates is fundamental to Angular.
Exercise
Create components with different types of data binding.
// user.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-user',
template: `
<div class="user-card">
<h2>{{ user.name }}</h2>
<p>Email: {{ user.email }}</p>
<p>Age: {{ user.age }}</p>
<input [(ngModel)]="user.name" placeholder="Enter name">
<button (click)="updateUser()">Update User</button>
<div *ngIf="user.isActive" class="active-badge">
Active User
</div>
</div>
`,
styles: [`
.user-card {
border: 1px solid #ccc;
padding: 15px;
margin: 10px;
border-radius: 5px;
}
.active-badge {
background: green;
color: white;
padding: 5px 10px;
border-radius: 3px;
margin-top: 10px;
}
`]
})
export class UserComponent {
user = {
name: 'John Doe',
email: 'john@example.com',
age: 30,
isActive: true
};
updateUser() {
console.log('User updated:', this.user);
}
}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { UserComponent } from './user.component';
@NgModule({
declarations: [AppComponent, UserComponent],
imports: [BrowserModule, FormsModule],
bootstrap: [AppComponent]
})
export class AppModule { }
Exercise Tips
- Try different data binding types: interpolation, property binding, event binding.
- Experiment with structural directives: *ngIf, *ngFor, *ngSwitch.
- Create child components and use @Input() to pass data.
- Use @Output() to emit events from child to parent components.