Skip to content

fix(form:cascader): set input id so <label for> resolves - #2038

Open
viejopool wants to merge 1 commit into
ng-alain:masterfrom
viejopool:fix-form-cascader-label-id
Open

fix(form:cascader): set input id so <label for> resolves#2038
viejopool wants to merge 1 commit into
ng-alain:masterfrom
viejopool:fix-form-cascader-label-id

Conversation

@viejopool

Copy link
Copy Markdown

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

[x] Bugfix
[ ] Feature
[ ] Code style update (formatting, local variables)
[ ] Refactoring (no functional changes, no api changes)
[ ] Build related changes
[ ] CI related changes
[ ] Documentation content changes
[ ] Application (the showcase website) / infrastructure changes
[ ] Other... Please describe:

What is the current behavior?

The CascaderWidget renders a <label [attr.for]="id"> via sf-item-wrap, but never sets that id on the inner <input> rendered by nz-cascader. As a result the label's for attribute points to a non-existent element, which fails the Lighthouse/axe "Incorrect use of <label for=FORM_ELEMENT>" audit.

Rendered DOM before the fix:

<nz-form-item>
  <div class="ant-form-item-label">
    <label for="_sf-0"><span>Location</span></label>  <!-- for points to _sf-0 -->
  </div>
  <nz-form-control>
    <nz-cascader>
      <input type="text" />  <!-- id is empty -->
    </nz-cascader>
  </nz-form-control>
</nz-form-item>

document.getElementById('_sf-0') returns null → the <label for> is broken and screen readers cannot associate the label with the control.

This is the same class of accessibility bug that was fixed for the abc:se widget in #1993 (commit 61cbe73, v21.1.0), but the form:cascader widget was not covered.

Why the se approach does not apply directly: the se fix sets the id on the control's elementRef (a native <input>), which is labelable. The nz-cascader host element is a custom element and not labelable, so the id must be set on the inner <input> it renders — which requires querying the DOM after nz-cascader has rendered.

Issue Number: N/A

What is the new behavior?

The widget overrides afterViewInit() to set the widget id on the inner <input> rendered by nz-cascader (deferred one microtask so the input exists), and re-syncs it after reset() since the input may be recreated when data loads.

override afterViewInit(): void {
  Promise.resolve().then(() => this.syncInputId());
}

override reset(value: SFValue): void {
  getData(this.schema, {}, value).subscribe(list => {
    this.data = list;
    this.detectChanges();
    Promise.resolve().then(() => this.syncInputId());
  });
}

private syncInputId(): void {
  if (!this.id) return;
  const input = (this.host.nativeElement as HTMLElement).querySelector('input');
  if (input) {
    input.id = this.id;
  }
}

Now the inner input carries the same id the <label for> points to, and the Lighthouse audit passes.

Does this PR introduce a breaking change?

[ ] Yes
[x] No

The change only adds an id attribute to an existing <input>; no public API, selector, or behavior changes.

Other information

  • Regression test added in widget.spec.ts under a new [accessibility] describe block, asserting that the inner <input> id matches the <label for> value.
  • Full test suite passes: 1896 SUCCESS, 0 FAILED (7 pre-existing skips).
  • tsc -p packages/tsconfig.json --noEmit and ESLint both clean.

The CascaderWidget renders a `<label [attr.for]="id">` via sf-item-wrap,
but never sets that id on the inner `<input>` rendered by nz-cascader.
As a result the label's `for` attribute points to a non-existent element,
failing the Lighthouse/axe 'Incorrect use of <label for=FORM_ELEMENT>' audit.

Unlike the abc:se fix (61cbe73), the id cannot be set on the control's
elementRef directly because the nz-cascader host element is not a labelable
element — the id must go on the inner <input>.

Fix: override afterViewInit() to set the id on the inner <input> after
nz-cascader renders it (deferred one microtask), and re-sync after reset()
since the input may be recreated when data loads.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request improves accessibility for the cascader widget by dynamically syncing the ID of the inner input element with the widget's ID, ensuring that the associated label's 'for' attribute resolves correctly. The changes include querying the input element asynchronously during view initialization and after data resets, along with adding a unit test to verify this behavior. The review feedback suggests removing a redundant type assertion on 'this.host.nativeElement' and replacing 'document.querySelector' with 'page.getEl' in the unit test to avoid potential test pollution.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.


private syncInputId(): void {
if (!this.id) return;
const input = (this.host.nativeElement as HTMLElement).querySelector('input');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The this.host property is already typed as ElementRef<HTMLElement>, so this.host.nativeElement is guaranteed to be of type HTMLElement. The type assertion as HTMLElement is redundant and can be safely removed to simplify the code.

Suggested change
const input = (this.host.nativeElement as HTMLElement).querySelector('input');
const input = this.host.nativeElement.querySelector('input');
References
  1. Prefer type inference when the type is obvious. Since ElementRef is already typed as ElementRef, the type of nativeElement is inferred as HTMLElement, making the type assertion redundant. (link)

const forId = labelEl.getAttribute('for')!;
expect(forId).toMatch(/^_sf-\d+$/);

const inputEl = document.querySelector('nz-cascader input') as HTMLInputElement;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using document.querySelector in unit tests can query elements outside the current test fixture or lead to test pollution if multiple tests run. Since page.getEl is already used in this test suite (e.g., on line 150), it is safer and more consistent to use page.getEl('nz-cascader input') instead.

Suggested change
const inputEl = document.querySelector('nz-cascader input') as HTMLInputElement;
const inputEl = page.getEl('nz-cascader input') as HTMLInputElement;

@codecov

codecov Bot commented Jun 16, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.15%. Comparing base (569e8ac) to head (a75197d).
⚠️ Report is 4 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff            @@
##           master    #2038    +/-   ##
========================================
  Coverage   95.14%   95.15%            
========================================
  Files         270      270            
  Lines        8776     8785     +9     
  Branches     1811     1708   -103     
========================================
+ Hits         8350     8359     +9     
  Misses        338      338            
  Partials       88       88            

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

export class CascaderWidget extends ControlUIWidget<SFCascaderWidgetSchema> implements OnInit {
static readonly KEY = 'cascader';

private readonly host = inject(ElementRef<HTMLElement>);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be more reliable to use:

private readonly comp = viewChild.required<NzCascaderComponent>('comp');

and then access the input element via this.comp().input?.id.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants