From 7e111a434a61213433cc62b246aadd1d1b27f5d8 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Mon, 18 May 2026 09:21:24 +0200 Subject: [PATCH] refactor(core): update internal utility Updates the `getClosestComponentName` function to add support for a predicate function, based on internal requirements. --- .../internal/get_closest_component_name.ts | 9 ++++++-- .../core/test/acceptance/internal_spec.ts | 21 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/core/src/internal/get_closest_component_name.ts b/packages/core/src/internal/get_closest_component_name.ts index 9d3809b5c7c3..93a2a8f9c191 100644 --- a/packages/core/src/internal/get_closest_component_name.ts +++ b/packages/core/src/internal/get_closest_component_name.ts @@ -17,8 +17,13 @@ import {getTNode} from '../render3/util/view_utils'; * Warning! this function will return minified names if the name of the component is minified. The * consumer of the function is responsible for resolving the minified name to its original name. * @param node Node from which to start the search. + * @param predicate Predicate function that can be used to decide which nodes should be skipped over + * during the search. Return true if the search should stop or false to keep going up the tree. */ -export function getClosestComponentName(node: Node): string | null { +export function getClosestComponentName( + node: Node, + predicate?: (current: HTMLElement, componentName: string) => boolean, +): string | null { let currentNode = node as Node | null; while (currentNode) { @@ -40,7 +45,7 @@ export function getClosestComponentName(node: Node): string | null { // Note: the name may be an empty string if the class name is // dropped due to minification. In such cases keep going up the tree. - if (name !== null) { + if (name !== null && (!predicate || predicate(currentNode as HTMLElement, name))) { return name; } else { break; diff --git a/packages/core/test/acceptance/internal_spec.ts b/packages/core/test/acceptance/internal_spec.ts index b56075cab1b1..6d8273956a39 100644 --- a/packages/core/test/acceptance/internal_spec.ts +++ b/packages/core/test/acceptance/internal_spec.ts @@ -143,5 +143,26 @@ describe('internal utilities', () => { ); ref.destroy(); }); + + it('should be able to skip over components', () => { + @Component({ + selector: 'comp', + template: '
', + }) + class Comp {} + + @Component({ + template: `
`, + imports: [Comp], + }) + class App {} + + const fixture = TestBed.createComponent(App); + fixture.detectChanges(); + const target = fixture.nativeElement.querySelector('.target'); + + expect(getClosestComponentName(target)).toBe('Comp'); + expect(getClosestComponentName(target, (el) => el.tagName !== 'COMP')).toBe('App'); + }); }); });