user2828442
user2828442

Reputation: 2515

onChange() should match the last typed alphabet, not the entire line every time

Explanation: I am using onChange function to find if someone types @

Problem: As I type it keeps on checking the entire line every time which makes typing sluggish. I want to modify my code so that it only checks the last alphabet which was typed.

My code:

home.html

<ion-textarea #chat [(ngModel)]="tag" rows="1" cols="10" placeholder="Type your message..." (ngModelChange)='onChange($event)'></ion-textarea>

home.ts

onChange(eve)
{
if(eve.match(/@/g).length > 0)

This is making typing experience sluggish because it checks the whole line every time, I want it should only check the last typed alphabet.

Upvotes: 1

Views: 79

Answers (3)

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try like this:

Template:

<ion-textarea #chat [(ngModel)]="tag" rows="1" cols="10" placeholder="Type your message..." (keydown)="onType($event)"></ion-textarea>

Typescript:

onType(event) {
    if (event.key == '@') {
      console.log("@ typed")
    }
  }

Working Demo

Upvotes: 1

paras shah
paras shah

Reputation: 889

you can try this to find last alphabets.

onChange(eve) {   
  eve = eve.split('')[eve.length-1] 
  if(eve.match(/@/g).length > 0) 
  ...
}

Upvotes: 0

Przemek Struciński
Przemek Struciński

Reputation: 5238

You can use keydown event:

<input (keydown)="onKeydown($event)">

Then you can handle it like this:

onKeydown(event) {
  if(event.key === "@")
  {  
    // your code
  }
}

But if you would like to just check last character in your string for onChange then you can do it this way:

if(eve.slice(-1) === '@') {}

Upvotes: 1

Related Questions