Angular & Signals (283 Qs)•Part 1: Architecture, Components, Directives & Lifecycle (1 - 35)
What are the differences between Component and Directive?
In a short note, A component(@component) is a directive-with-a-template.
Some of the major differences are mentioned in a tabular form
| Component | Directive |
|---|---|
| To register a component we use @Component meta-data annotation | To register a directive we use @Directive meta-data annotation |
| Components are typically used to create UI widgets | Directives are used to add behavior to an existing DOM element |
| Component is used to break down the application into smaller components | Directive is used to design re-usable components |
| Only one component can be present per DOM element | Many directives can be used per DOM element |
| @View decorator or templateurl/template are mandatory | Directive doesn't use View |
Practical Code Example
typescript
// Component: Directive WITH a view template
@Component({
selector: 'app-card',
standalone: true,
template: `<div class="card"><ng-content></ng-content></div>`
})
export class CardComponent {}
// Directive: Attaches custom behavior to an existing DOM element WITHOUT its own template
@Directive({
selector: '[appHighlight]',
standalone: true
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}