Antoine Muresan
Antoine Muresan

Reputation: 27

How to get focus on Ion Input

Hello I am new to ionic / angular.

This is a small project in Ionic4 and I want to get a IonInput Focus status.

I have been looking at the documentation and forum for a bit and didn't found something that helped me.

I know there is a IonFocus event that triggers when the input has focus but it doesn't tell me if the input is focused at a given moment.

What I am looking for is something like in Ionic 3 when you could do this with a TextInput :

let hasFocus = textInput.isFocus();

Upvotes: 0

Views: 1948

Answers (1)

ierhalim
ierhalim

Reputation: 298

I'm not familiar with ionic but you can always use angular directives to register events and store the current state.

So I check the ionic docs and saw 2 event that I can use.

ionBlur Emitted when the input loses focus.

ionFocus Emitted when the input has focus.

import { Directive, EventEmitter, Input, OnInit, Output, Self } from '@angular/core';
import { IonInput } from '@ionic/angular';

    @Directive({
        selector: '[appFocusState]',
    })
    export class FocusStateDirective implements OnInit {
    
        constructor(@Self() private readonly ionInput: IonInput) { }
    
        private _hasFocus: boolean;
    
        @Input('appFocusState')
        set hasFocus(value: boolean) {
            this._hasFocus = value;
            // Also you can support setted focus via appFocusState input.
            if (this._hasFocus) {
                this.ionInput.setFocus();
            } else{
                // If yo want to support focus out when hasFocus property setting to false, you should check the ionic docs and find a way to support focusOut.
            }
        }
    
        // Required to support two level binding.
        @Output('appFocusStateChange')
        hasFocusChange = new EventEmitter<boolean>();
    
        get hasFocus() {
            return this._hasFocus;
        }
        ngOnInit(): void {
            this.ionInput.ionBlur.subscribe(() => {
                if (this._hasFocus) { 
                    this._hasFocus = false;
                    this.hasFocusChange.next(this._hasFocus);
                }
            });
    
            this.ionInput.ionFocus.subscribe(()=>{
                if(!this._hasFocus){
                    this._hasFocus = true;
                    this.hasFocusChange.next(this._hasFocus);
                }
            });
        }
    }

When you add this directive to declarations of your module you can check focus state.

  <ion-label>Focus State {{fooInputFocusState}}</ion-label>
  <ion-input [(appFocusState)]="fooInputFocusState" ></ion-input>

Upvotes: 1

Related Questions