I know that this might help some users out there. This is what I have done in the past. I have created an Angular ID Service
that keeps track of all of the ids that I have generated throughout the project. Each time an id is generated, it is checked against all of the other ids to ensure that it is unique. There are one public property and two public methods.
Remember
You must generate a new id in the ngOnInit
method and remove that id in the ngOnDestroy
method. If you fail to remove the id when the component is destroyed, they the ids array will get very large.
Code
ids: string[]
: This is a list of all unique ids stored in the service to ensure uniqueness.
generate(): string
: This method will generate and return a unique id as a string; Output: E.g. bec331aa-1566-1f59-1bf1-0a709be9a710
remove(id: string): void
: This method will remove a given id from the stored ids' array.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class IdService { public ids: string[] = []; constructor() {} public generate(): string { let isUnique = false; let tempId = ''; while (!isUnique) { tempId = this.generator(); if (!this.idExists(tempId)) { isUnique = true; this.ids.push(tempId); } } return tempId; } public remove(id: string): void { const index = this.ids.indexOf(id); this.ids.splice(index, 1); } private generator(): string { const isString = `${this.S4()}${this.S4()}-${this.S4()}-${this.S4()}-${this.S4()}-${this.S4()}${this.S4()}${this.S4()}`; return isString; } private idExists(id: string): boolean { return this.ids.includes(id); } private S4(): string { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); } }