From 755bf1a676bf072325e1d5ec2de54ef59e36f2d4 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Thu, 31 Oct 2024 14:01:50 +0100 Subject: [PATCH] refactor(material/slide-toggle): use ID generator Switches to using the ID generator service to create unique IDs. (cherry picked from commit 621ec01d8ebc1d37c522645b7b2b347904f6469a) --- src/material/slide-toggle/slide-toggle.spec.ts | 4 ++-- src/material/slide-toggle/slide-toggle.ts | 7 ++----- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/material/slide-toggle/slide-toggle.spec.ts b/src/material/slide-toggle/slide-toggle.spec.ts index 1433026fadc4..8a775f2f66f8 100644 --- a/src/material/slide-toggle/slide-toggle.spec.ts +++ b/src/material/slide-toggle/slide-toggle.spec.ts @@ -173,7 +173,7 @@ describe('MatSlideToggle without forms', () => { fixture.detectChanges(); // Once the id binding is set to null, the id property should auto-generate a unique id. - expect(buttonElement.id).toMatch(/mat-mdc-slide-toggle-\d+-button/); + expect(buttonElement.id).toMatch(/mat-mdc-slide-toggle-\w+\d+-button/); }); it('should forward the tabIndex to the underlying element', () => { @@ -235,7 +235,7 @@ describe('MatSlideToggle without forms', () => { // We fall back to pointing to the label if a value isn't provided. expect(buttonElement.getAttribute('aria-labelledby')).toMatch( - /mat-mdc-slide-toggle-\d+-label/, + /mat-mdc-slide-toggle-\w+\d+-label/, ); }); diff --git a/src/material/slide-toggle/slide-toggle.ts b/src/material/slide-toggle/slide-toggle.ts index b5969838eea4..b1fe596d1bb0 100644 --- a/src/material/slide-toggle/slide-toggle.ts +++ b/src/material/slide-toggle/slide-toggle.ts @@ -35,7 +35,7 @@ import { ValidationErrors, Validator, } from '@angular/forms'; -import {FocusMonitor} from '@angular/cdk/a11y'; +import {_IdGenerator, FocusMonitor} from '@angular/cdk/a11y'; import { MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS, MatSlideToggleDefaultOptions, @@ -63,9 +63,6 @@ export class MatSlideToggleChange { ) {} } -// Increasing integer for generating unique ids for slide-toggle components. -let nextUniqueId = 0; - @Component({ selector: 'mat-slide-toggle', templateUrl: 'slide-toggle.html', @@ -220,7 +217,7 @@ export class MatSlideToggle this.tabIndex = tabIndex == null ? 0 : parseInt(tabIndex) || 0; this.color = defaults.color || 'accent'; this._noopAnimations = animationMode === 'NoopAnimations'; - this.id = this._uniqueId = `mat-mdc-slide-toggle-${++nextUniqueId}`; + this.id = this._uniqueId = inject(_IdGenerator).getId('mat-mdc-slide-toggle-'); this.hideIcon = defaults.hideIcon ?? false; this.disabledInteractive = defaults.disabledInteractive ?? false; this._labelId = this._uniqueId + '-label';