diff --git a/src/cdk/platform/features/backwards-compatibility.ts b/src/cdk/platform/features/backwards-compatibility.ts new file mode 100644 index 000000000000..717f880d7654 --- /dev/null +++ b/src/cdk/platform/features/backwards-compatibility.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import {Renderer2, VERSION, ListenerOptions} from '@angular/core'; + +// TODO(crisbeto): remove this function when making breaking changes for v20. +/** + * Binds an event listener with specific options in a backwards-compatible way. + * This function is necessary, because `Renderer2.listen` only supports listener options + * after 19.1 and during the v19 period we support any 19.x version. + * @docs-private + */ +export function _bindEventWithOptions( + renderer: Renderer2, + target: EventTarget, + eventName: string, + callback: (event: any) => boolean | void, + options: ListenerOptions, +): () => void { + const major = parseInt(VERSION.major); + const minor = parseInt(VERSION.minor); + + // Event options in `listen` are only supported in 19.1 and beyond. + // We also allow 0.0.x, because that indicates a build at HEAD. + if (major > 19 || (major === 19 && minor > 0) || (major === 0 && minor === 0)) { + return renderer.listen(target, eventName, callback, options); + } + + target.addEventListener(eventName, callback, options); + + return () => { + target.removeEventListener(eventName, callback, options); + }; +} diff --git a/src/cdk/platform/public-api.ts b/src/cdk/platform/public-api.ts index ae1990dee0fe..9613cc5b04bc 100644 --- a/src/cdk/platform/public-api.ts +++ b/src/cdk/platform/public-api.ts @@ -13,3 +13,4 @@ export * from './features/passive-listeners'; export * from './features/scrolling'; export * from './features/shadow-dom'; export * from './features/test-environment'; +export * from './features/backwards-compatibility'; diff --git a/tools/public_api_guard/cdk/platform.md b/tools/public_api_guard/cdk/platform.md index 9259ee1672a1..a93b2f19e708 100644 --- a/tools/public_api_guard/cdk/platform.md +++ b/tools/public_api_guard/cdk/platform.md @@ -5,6 +5,11 @@ ```ts import * as i0 from '@angular/core'; +import { ListenerOptions } from '@angular/core'; +import { Renderer2 } from '@angular/core'; + +// @public +export function _bindEventWithOptions(renderer: Renderer2, target: EventTarget, eventName: string, callback: (event: any) => boolean | void, options: ListenerOptions): () => void; // @public export function _getEventTarget(event: Event): T | null;