Angular Components
Components are the fundamental building blocks of Angular applications. They control a portion of the screen (a view) through its associated template.
What is a Component?
A component consists of:
- A TypeScript class that defines behavior
- An HTML template that defines the view
- Optional CSS styles
Creating a Component
You can create a component using the Angular CLI:
ng generate component component-name
Or manually by creating these files:
component-name.component.ts
- The component classcomponent-name.component.html
- The templatecomponent-name.component.css
- The styles (optional)
Component Example
Here's a basic component example:
// greeting.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
templateUrl: './greeting.component.html',
styleUrls: ['./greeting.component.css']
})
export class GreetingComponent {
name = 'Angular';
count = 0;
increment() {
this.count++;
}
}
<!-- greeting.component.html -->
<div>
<h1>Hello {{name}}!</h1>
<p>Count: {{count}}</p>
<button (click)="increment()">Increment</button>
</div>
/* greeting.component.css */
div {
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
max-width: 300px;
}
button {
padding: 5px 10px;
background-color: #1abc9c;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
}
Component Metadata
The @Component
decorator provides metadata:
- selector: The CSS selector that identifies this component in a template
- templateUrl: Path to the HTML template
- styleUrls: Array of paths to style files
- template: Inline template (alternative to templateUrl)
- styles: Inline styles (alternative to styleUrls)
Component Lifecycle Hooks
Angular components have lifecycle hooks that allow you to tap into key moments:
- ngOnChanges: Called when input properties change
- ngOnInit: Called after first ngOnChanges
- ngDoCheck: Custom change detection
- ngAfterContentInit: After content projected into view
- ngAfterContentChecked: After projected content checked
- ngAfterViewInit: After component's view initialized
- ngAfterViewChecked: After component's view checked
- ngOnDestroy: Just before the component is destroyed
Component Communication
Components can communicate in several ways:
- Input Properties: Pass data from parent to child
- Output Events: Emit events from child to parent
- ViewChild: Access child component from parent
- Services: Share data between unrelated components
Input Example
// child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `<p>{{message}}</p>`
})
export class ChildComponent {
@Input() message: string;
}
// parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child [message]="parentMessage"></app-child>
`
})
export class ParentComponent {
parentMessage = 'Hello from parent';
}
Output Example
// child.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendMessage()">Send Message</button>
`
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit('Hello from child');
}
}
// parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>{{message}}</p>
`
})
export class ParentComponent {
message: string;
receiveMessage($event) {
this.message = $event;
}
}
Component Best Practices
- Keep components small and focused
- Use smart and dumb component pattern
- Minimize business logic in components
- Use OnPush change detection when possible
- Prefer input/output over direct access