Trigger ion-input focus when ion-icon clicked

#1

Good day all

I am building my first ionic 4 mobile application, and have a question about how label, icons and other elements can be connected to a form input.

In normal HTML forms you have a relationship between labels and inputs using the “for” attribute, like so:

<label for="name">Please enter name</label>
<input type="text" id="name" name="name"/> 

With this relationship in place the input field gains focus when you either click on the label or on the input itself to gain focus on the input.

In ionic you use ion-label and ion-input instead of the default HTML form elements, and these seem to not share this capability.

I am specifically interested in using an icon as the aforementioned label. I tried the following without any success:

<ion-item>
  <ion-label for="searchText">
    <ion-icon name="search"></ion-icon> <!--name here refers to the icon displayed-->
  </ion-label>
  <ion-input id="searchText" name="searchText" type="text" placeholder="Search" ></ion-input>
</ion-item>

Is there something similar that one can use, or do I need to use JavaScript to achieve this?

Any advice would be greatly appropriated

#2

Just use a (click) function in ion-icon.
in your ts file get view child with this:

@ViewChild('inputid') myInput: TextInput;

and in the click function:

this.myInput.setFocus();

Hope this helps you.

#3

Thanks for the suggestion @mavillavishnu. I had thought about that, but was hoping to find a solutions that did not require JavaScript. At this point it seems it is the only way however :slight_smile:

1 Like