javascript / intermediate
Snippet
Inheriting Shared Component Logic with Abstract Base Classes
Abstract classes in Angular allow components to inherit common state, injected dependencies, and helper methods. Applying @Directive() to the abstract base class is required so Angular's compiler processes dependency injection properly in subclasses.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { Directive, inject, DestroyRef } from '@angular/core';@Directive()export abstract class BaseCardWidget {protected destroyRef = inject(DestroyRef);abstract widgetTitle: string;protected logAction(action: string): void {console.log(`[${this.widgetTitle}] Executing: ${action}`);}}
angular
Breakdown
1
export abstract class BaseCardWidget {
Defines an abstract base class that cannot be instantiated directly and serves as a blueprint for concrete components.
2
abstract widgetTitle: string;
Forces all inheriting child components to implement their own specific title property.
3
protected logAction(action: string): void {
Encapsulates a reusable helper method accessible only to this class and its derived subclasses.