Skip to content

Commit

Permalink
fix(slide-toggle): redirect focus to underlying input element (#13957)
Browse files Browse the repository at this point in the history
Currently the `mat-slide-toggle` doesn't redirect focus to the underlying `input` element. This means that things like the focus trap's `cdkFocusInitial` won't work when they're set on the toggle host. These changes add a `tabindex` and set up a `focus` listener to forward focus to the input.

Relates to #13953.
  • Loading branch information
crisbeto authored and vivian-hu-zz committed Nov 7, 2018
1 parent fa944b7 commit ec4809f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/lib/slide-toggle/slide-toggle.spec.ts
Expand Up @@ -293,6 +293,15 @@ describe('MatSlideToggle without forms', () => {
expect(document.activeElement).toBe(inputElement);
});

it('should focus on underlying input element when the host is focused', () => {
expect(document.activeElement).not.toBe(inputElement);

slideToggleElement.focus();
fixture.detectChanges();

expect(document.activeElement).toBe(inputElement);
});

it('should set a element class if labelPosition is set to before', () => {
expect(slideToggleElement.classList).not.toContain('mat-slide-toggle-label-before');

Expand Down Expand Up @@ -355,7 +364,7 @@ describe('MatSlideToggle without forms', () => {
fixture.detectChanges();

const slideToggle = fixture.debugElement.query(By.directive(MatSlideToggle)).nativeElement;
expect(slideToggle.getAttribute('tabindex')).toBeFalsy();
expect(slideToggle.getAttribute('tabindex')).toBe('-1');
}));
});

Expand Down
3 changes: 2 additions & 1 deletion src/lib/slide-toggle/slide-toggle.ts
Expand Up @@ -86,11 +86,12 @@ export const _MatSlideToggleMixinBase:
host: {
'class': 'mat-slide-toggle',
'[id]': 'id',
'[attr.tabindex]': 'null',
'[attr.tabindex]': '-1', // Needs to be `-1` so it can still receive programmatic focus.
'[class.mat-checked]': 'checked',
'[class.mat-disabled]': 'disabled',
'[class.mat-slide-toggle-label-before]': 'labelPosition == "before"',
'[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"',
'(focus)': '_inputElement.nativeElement.focus()',
},
templateUrl: 'slide-toggle.html',
styleUrls: ['slide-toggle.css'],
Expand Down

0 comments on commit ec4809f

Please sign in to comment.