Skip to content

Commit cea4d9f

Browse files
authored
fix(radio): forward focus to native input (#6274)
* fix(radio): forward focus to native input * add comment
1 parent 9df292f commit cea4d9f

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/lib/radio/radio.spec.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ describe('MdRadio', () => {
1515
TestBed.configureTestingModule({
1616
imports: [MdRadioModule, FormsModule, ReactiveFormsModule],
1717
declarations: [
18+
FocusableRadioButton,
1819
RadiosInsideRadioGroup,
1920
RadioGroupWithNgModel,
2021
RadioGroupWithFormControl,
@@ -640,6 +641,27 @@ describe('MdRadio', () => {
640641
}
641642
});
642643
});
644+
645+
describe('with tabindex', () => {
646+
let fixture: ComponentFixture<FocusableRadioButton>;
647+
648+
beforeEach(() => {
649+
fixture = TestBed.createComponent(FocusableRadioButton);
650+
fixture.detectChanges();
651+
});
652+
653+
it('should forward focus to native input', () => {
654+
let radioButtonEl = fixture.debugElement.query(By.css('.mat-radio-button')).nativeElement;
655+
let inputEl = fixture.debugElement.query(By.css('.mat-radio-input')).nativeElement;
656+
657+
radioButtonEl.focus();
658+
// Focus events don't always fire in tests, so we needc to fake it.
659+
dispatchFakeEvent(radioButtonEl, 'focus');
660+
fixture.detectChanges();
661+
662+
expect(document.activeElement).toBe(inputEl);
663+
});
664+
});
643665
});
644666

645667

@@ -728,3 +750,8 @@ class RadioGroupWithNgModel {
728750
class RadioGroupWithFormControl {
729751
formControl = new FormControl();
730752
}
753+
754+
@Component({
755+
template: `<md-radio-button tabindex="-1"></md-radio-button>`
756+
})
757+
class FocusableRadioButton {}

src/lib/radio/radio.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,10 @@ export const _MdRadioButtonMixinBase = mixinColor(mixinDisableRipple(MdRadioButt
332332
'[class.mat-radio-checked]': 'checked',
333333
'[class.mat-radio-disabled]': 'disabled',
334334
'[attr.id]': 'id',
335+
// Note: under normal conditions focus shouldn't land on this element, however it may be
336+
// programmatically set, for example inside of a focus trap, in this case we want to forward
337+
// the focus to the native element.
338+
'(focus)': '_inputElement.nativeElement.focus()',
335339
},
336340
changeDetection: ChangeDetectionStrategy.OnPush,
337341
})

0 commit comments

Comments
 (0)