fix(slide-toggle): redirect focus to underlying input element (#13957)

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.
This commit is contained in:
Kristiyan Kostadinov
2018-11-07 18:19:07 +00:00
committed by vivian-hu
parent fa944b7fe4
commit ec4809ff1b
2 changed files with 12 additions and 2 deletions
+10 -1
View File
@@ -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');
@@ -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');
}));
});
+2 -1
View File
@@ -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'],