Click here to Skip to main content
14,699,605 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi All,

I am trying to implement focus() on form elements in Angular 10.

I thought it was quite simple. I tried in Angular way which was using ElementRef and even tried with basic javascript code - document.getElementById(..).

But, nothing worked out successfully and I really cannot understand the reason.

What I have tried:

I have tried in two ways:

1. Javascript code in .ts (typescript) file
document.getElementById("inputSearch").focus();


2. Angular way

test.component.html
<form class="form-horizontal fonts" autocomplete="off" action="" ngSubmit)="onSubmit()">
<div class="form-group">
<label class="control-label" for="prmCorrSelect">Correlation</label>
<select id="prmCorrSelect" #drop class="form-control input-types fonts" name="prmCorrSelect">
   <option *ngFor="let data of correlationList" [value]="data.Id">{{data.Correlation}} 
   </option>
</select>


test.component.ts
import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

export class export class TestComponent implements OnInit {

  @ViewChild("drop") nameField: ElementRef;

  ngOnInit(): void {
    this.nameField.nativeElement.focus();
  }
}


I don't know why none of these is working for me.
Posted
Updated 4 days ago
v2

Here, the code works fine: form-focus element Angular way[^]
import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  @ViewChild("name") nameField: ElementRef;
  editName() {
    this.nameField.nativeElement.focus();
  }
}
Check out.
   
Comments
Member 11072126 4-Sep-20 21:18pm
   
Hi, Thanks for the response.
I have updated my question and posted the html and ts file. I am trying to put the focus on a dropdown item, on page load. Am not sure but do I need to add any pther properties for form element, to make this thing work out?
Or does it work with "mat-Input" attribues only?
import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

export class export class TestComponent implements OnInit {

@ViewChild("drop") nameField: ElementRef;

ngOnInit(): void {

setTimeout(()=>{
this.nameField.nativeElement.focus();
},100)

}
}
   
v2
try adding tabindex="0" to the component, it allows it to be focusable
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900