Reputation: 149
I have the following code in Angular 5:
<select class="abc" (change)="items($event)" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
When a user selects any particular of the above option, the focus goes onto the selected option. I'm trying to get any selected option out of focus(after the user selects any option) and would to like to shift focus on a different element of the DOM(if required).
I tried getElementById with focus()
but it doesn't seem to work.
items(event)
{
ABC Code;
Shifting focus code goes here;
}
Upvotes: 0
Views: 997
Reputation: 18647
Here is a working solution in Angular way using Renderer2
HTML:
<select class="abc" (change)="change()" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="text" id="myInput">
<input type="text">
Component:
import { Component, Renderer2 } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(public renderer2: Renderer2){
}
change(){
let onElement = this.renderer2.selectRootElement('#myInput');
onElement.focus();
}
}
Upvotes: 2
Reputation:
This is standard Javascript and as you can see it works, if you have an error you need to provide a sandbox reproducing the said error. Pseudo-code isn't enough to identify the issue.
function focusInput(value) {
document.querySelector('input#input-' + value).focus();
}
<select onchange="focusInput(this.value)" palceholder="select an input to focus">
<option value="0">Input 0</option>
<option value="1">Input 1</option>
<option value="2">Input 2</option>
</select>
<input type="text" id="input-0" placeholder="Input 0" style="display: block;">
<input type="text" id="input-1" placeholder="Input 1" style="display: block;">
<input type="text" id="input-2" placeholder="Input 2" style="display: block;">
Upvotes: 0
Reputation: 3574
Suppose your different element is this:
<input type="text" #inputText>
Then you can try this:
<select class="abc" (change)="inputText.focus()" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Upvotes: 0