Reputation: 9443
How do we focus the md-tab first element (e.g. input) when we programmatically changed the md-tab selectedIndex
?
Template
<md-tab-group #tg>
<md-tab label="Tab1">
<button md-button (click)="nextTab(tg)">Goto tab 2</button>
</md-tab>
<md-tab label="Tab2">
<md-form-field>
<input id="_input1" mdInput #input1>
</md-form-field>
<md-form-field>
<input id="_input2" mdInput #input2>
</md-form-field>
</md-tab>
<md-tab-group>
TS
@ViewChild('input1') vcInput1: any;
nextTab(tab: any): void {
setTimeout(_=> {
// tab changes to Tab2
this.vcTg.selectedIndex = 1;
// nothing happened
this.vcInput1.nativeElement.focus();
// null
console.log(document.getElementById('_input1'))
})
}
Despite searching any related problem. I couldn't find the right explanation and solution.
Upvotes: 1
Views: 2435
Reputation: 34673
Do the focus of input in (selectChange)
event of MdTabGroup
and get your input1
as ElementRef
. Here is the code:
In you html template:
<md-tab-group #tg (selectChange)="tabSelectionChanged($event)">
and in your ts code:
@ViewChild('input1') vcInput1: ElementRef;
nextTab(): void {
// tab changes to Tab2
this.vcTg.selectedIndex = 1;
}
tabSelectionChanged(event: MdTabChangeEvent){
if(event.index === 1){
this.vcInput1.nativeElement.focus();
}
}
Link to working demo.
Upvotes: 1
Reputation: 28708
Use (selectChange) event to detect which tab is selected:
Typescript:
@ViewChild('input1') vcInput1: any;
@ViewChild('input2') vcInput2: any;
nextTab(tab: any): void {
console.log(tab)
if(tab.index==0) {
// nothing happened
this.vcInput1.nativeElement.focus();
}
if(tab.index===1) {
// nothing happened
this.vcInput2.nativeElement.focus();
}
// null
}
HTML:
<md-tab-group (selectChange)="nextTab($event)" >
<md-tab label="Tab 1">Content 1
<input #input1>
</md-tab>
<md-tab label="Tab 2">Content 2
<input #input2 >
</md-tab>
</md-tab-group>
Upvotes: 1