javascript / intermediate
Snippet
Inheriting Shared Properties via Abstract Base Component Class
Object-oriented inheritance in Angular allows multiple components to inherit common input properties and computed getters from an abstract base class. Decorating the abstract class with @Directive() ensures Angular's compiler processes inputs and lifecycle hooks across child components.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { Directive, Input } from '@angular/core';export interface BaseEntity {id: string;createdAt: Date;}@Directive()export abstract class AbstractCardComponent<T extends BaseEntity> {@Input({ required: true }) data!: T;@Input() isHighlighted = false;get formattedDate(): string {return this.data.createdAt.toLocaleDateString();}}
angular
Breakdown
1
export interface BaseEntity {
Declares a generic data shape constraint requiring an id and a Date property.
2
@Directive()
Allows Angular to inherit metadata and input bindings on child classes without declaring a template.
3
export abstract class AbstractCardComponent<T extends BaseEntity> {
Defines an abstract base class parameterized with a generic entity type.
4
@Input({ required: true }) data!: T;
Enforces a required input property adhering to the generic entity type T.
5
get formattedDate(): string {
Provides a shared computed getter for formatting the entity creation timestamp.