Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular focus on input while clicking an element

I have attached the stackblitz below

https://stackblitz.com/edit/angular-dgx3pe

What i am trying to achieve is while clicking on the label element it should focus on the input.Hence the input:focus class gets activated.What I belive is that it can be achievable through javascript/jquery.But i prefer the angular way to achieve this.

In Brief,these are the two things i am trying to do,

  • Make focus on the input element when label is clicked.
  • When the focus is changed to another input element and if the previous element is not empty(If some value is typed in).The label should maintain its position in the top.

HTML

<input class="input" type="text">
<label class="label">Name</label>

<div>
<input class="input" type="text">
<label class="label">Name</label>
</div>

CSS

p {
  font-family: Lato;
}
.input
{
  border:none;
  border-bottom:1px solid grey;
  outline:none;
   margin-top:20%;
}
.input:focus
{
    border-bottom:1px solid orange;
}
.label
{
  position:relative;
 left:-170px;
}
.input:focus + .label
{
   bottom:20px;
}
like image 594
Sathya Narayanan GVK Avatar asked Mar 30 '26 22:03

Sathya Narayanan GVK


2 Answers

  1. In the html, add a reference to your input text - #firstNameField and add a method to click event of the label - (click)="focusOnFirstName()"
    <input #firstNameField class="input" type="text">
    <label class="label" (click)="focusOnFirstName()">First Name</label>

  1. In your component declare ViewChild and implement a method to click of label field.
      @ViewChild("firstNameField") firstNameField;

      focusOnFirstName(){
        this.firstNameField.nativeElement.focus();
      }


like image 197
Godwin Stanislaus Avatar answered Apr 02 '26 11:04

Godwin Stanislaus


You can do this with pure markup. You need to add an id to the input and a for element to the label

<input class="input" type="text" id="firstName">
<label class="label" for="firstName" >First Name</label>

This is just part of the html spec - labels can be associated with inputs - the out of the box functionality here is that on clicking a label it sets focus to its associated input. id and for attributes must match for this to work.

For the second part of your question, and to reuse your css classes - add matching variables to your component. Use ngClass to add the .go-top class when the variable has a value

In component -

firstName: string;

Then in the html -

  <input class="input" type="text" id="firstName" [(ngModel)]="firstName">
  <label class="label" for="firstName" [ngClass]="{'go-top': firstName}">First Name</label>
like image 25
dmoo Avatar answered Apr 02 '26 11:04

dmoo