Xi Xiao
Xi Xiao

Reputation: 973

How to unfocus ion-input when enter is hit

I have an ion-input to allow users to add text comments. I wish that when the text is not empty and user hits enter, the ion-input is unfocused automatically. Of course, I will implement logic to save the comment text to DB and show back in the page.

I tried both event.blur() and textInput.nativeElement.blur(), but not working. How to unfocus?

  commentHandler(event) {
    const keyCode = event.keyCode;
    if (keyCode === 13 && this.commentText != "") {
      this.logger.info("enter hit");
      event.blur();
      // this.textInput.nativeElement.blur();
    }
  }

<ion-item>
    <ion-label floating>Add comment, then hit enter</ion-label>
    <ion-input #commentInput type="text" (keypress)="commentHandler($event)" ngModel="commentText"></ion-input>
  </ion-item>

Upvotes: 1

Views: 4186

Answers (1)

Niels
Niels

Reputation: 1330

After searching and trying different things, this seems to work for me. Hope it helps.

myPage.ts:

import { ElementRef, ViewChild } from "@angular/core";

export class MyPage {
    @ViewChild('chatInput') chatInput: ElementRef;

    myFunction() {
        this.chatInput['_native'].nativeElement.blur();
    }
}

myPage.html:

<ion-input #chatInput ></ion-input>

Inspired by this page (but their solution did not work for me): https://forum.ionicframework.com/t/how-to-force-blur-on-ion-input/64038/6

Upvotes: 1

Related Questions