A convenient service is available that comprises two objects known as outerCounterMap
and innerCounterMap
. Their purpose is to store the counter values based on the component name.
The unique condition is that the outer counter can only be incremented once, specifically when its value is zero.
incrementOuterCounter(className: string): void {
if (!this.outerCounterMap[className]) {
this.outerCounterMap[className] = 0;
}
if (this.outerCounterMap[className] === 0) { // update only once!
this.internalInnerCounter++;
this.outerCounterMap[className] = this.internalInnerCounter;
}
}
Now, by using this.constructor.name
, we can extract the component name for tracking indexes in relation to this name. The maps of the service (outerCounterMap
and innerCounterMap
) will provide the desired output.
Complete Code:
one.component.ts
import { AfterViewInit, Component, OnDestroy } from '@angular/core';
import { CounterService } from '../../services/counter.service';
@Component({
selector: 'app-one',
standalone: true,
imports: [],
templateUrl: './one.component.html',
styleUrl: './one.component.css',
})
export class OneComponent {
className: string = this.constructor.name;
label: string = '';
constructor(public counter: CounterService) {
this.counter.incrementOuterCounter(this.className);
this.counter.incrementInnerCounter(this.className);
}
getLabel() {
return (
this.counter.getOuterCounter(this.className) +
'.' +
this.counter.getInnerCounter(this.className)
);
}
}
service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class CounterService {
private outerCounterMap: { [key: string]: number } = {};
private innerCounterMap: { [key: string]: number } = {};
internalInnerCounter = 0;
constructor() {}
getInnerCounter(className: string): number {
return this.innerCounterMap[className] || 0;
}
incrementInnerCounter(className: string): void {
if (!this.innerCounterMap[className]) {
this.innerCounterMap[className] = 0;
}
this.innerCounterMap[className] = this.innerCounterMap[className] + 1;
}
getOuterCounter(className: string): number {
return this.outerCounterMap[className] || 0;
}
incrementOuterCounter(className: string): void {
if (!this.outerCounterMap[className]) {
this.outerCounterMap[className] = 0;
}
if (this.outerCounterMap[className] === 0) {
this.internalInnerCounter++;
this.outerCounterMap[className] = this.internalInnerCounter;
}
}
}