Skip to content

Commit f4a54d6

Browse files
jelbournandrewseguin
authored andcommitted
refactor(cdk/overlay): use classList.toggle
With Angular dropping IE11 support in version 13, we can now use `classList.toggle` with the second `force` param. Related to #7374
1 parent d897a0c commit f4a54d6

File tree

3 files changed

+14
-13
lines changed

3 files changed

+14
-13
lines changed

src/cdk/overlay/overlay-ref.ts

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -469,15 +469,11 @@ export class OverlayRef implements PortalOutlet, OverlayReference {
469469

470470
/** Toggles a single CSS class or an array of classes on an element. */
471471
private _toggleClasses(element: HTMLElement, cssClasses: string | string[], isAdd: boolean) {
472-
const classList = element.classList;
472+
const classes = coerceArray(cssClasses || []).filter(c => !!c);
473473

474-
coerceArray(cssClasses).forEach(cssClass => {
475-
// We can't do a spread here, because IE doesn't support setting multiple classes.
476-
// Also trying to add an empty string to a DOMTokenList will throw.
477-
if (cssClass) {
478-
isAdd ? classList.add(cssClass) : classList.remove(cssClass);
479-
}
480-
});
474+
if (classes.length) {
475+
isAdd ? element.classList.add(...classes) : element.classList.remove(...classes);
476+
}
481477
}
482478

483479
/** Detaches the overlay content next time the zone stabilizes. */

src/cdk/overlay/overlay.spec.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,8 +451,17 @@ describe('Overlay', () => {
451451
const overlayRef = overlay.create();
452452
overlayRef.attach(componentPortal);
453453

454+
// Empty string
454455
expect(() => overlayRef.addPanelClass('')).not.toThrow();
455456
expect(() => overlayRef.removePanelClass('')).not.toThrow();
457+
458+
// Empty array
459+
expect(() => overlayRef.addPanelClass([])).not.toThrow();
460+
expect(() => overlayRef.removePanelClass([])).not.toThrow();
461+
462+
// Array containing only the empty string
463+
expect(() => overlayRef.addPanelClass([''])).not.toThrow();
464+
expect(() => overlayRef.removePanelClass([''])).not.toThrow();
456465
});
457466

458467
describe('positioning', () => {

src/dev-app/connected-overlay/connected-overlay-demo.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,7 @@ export class ConnectedOverlayDemo {
106106
const box = document.querySelector<HTMLElement>('.cdk-overlay-connected-position-bounding-box');
107107

108108
if (box) {
109-
if (showBoundingBox) {
110-
box.classList.add('demo-bounding-box-visible');
111-
} else {
112-
box.classList.remove('demo-bounding-box-visible');
113-
}
109+
box.classList.toggle('demo-bounding-box-visible', showBoundingBox);
114110
}
115111
}
116112
}

0 commit comments

Comments
 (0)