The onChange() function should only consider the last character typed, rather than evaluating the entire line each time

Explanation: I am utilizing the onChange function to detect when someone types the symbol @.

Issue: While typing, the code currently checks the entire line each time a character is added, causing a lag in typing speed. I am looking to update the code so it only checks the most recently typed character.

Snippet of 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)

The current implementation slows down the typing experience as it checks the entire line with each keystroke. I aim to optimize it to only examine the last character that was typed.

Answer №1

Here is a suggested way to implement it:

Template:

<ion-textarea #message [(ngModel)]="input" rows="2" cols="15" placeholder="Type your text..." (keypress)="onKeyPress($event)"></ion-textarea>

Typescript:

onKeyPress(event) {
    if (event.key == '!') {
      console.log("! key pressed")
    }
  }

Live Demo

Answer №2

To detect key presses, you can utilize the keydown event:

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

Here's how you can handle it:

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

Alternatively, if you only want to check the last character in a string for changes using onChange, you can do so like this:

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

Answer №3

If you're looking to identify the last alphabet in a string, you could use this method:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to differentiate between the legend and chart when working with three separate

I have encountered an issue with my pie charts. The first chart has 10 legends displayed below it, while the second chart only has 4 legends. When I adjust the padding to accommodate the 10 legends in the first chart, the names of the 4 legends in the se ...

"Utilizing the power of Angular 6's JSON pipe

Looking for a well-structured formatted JSON, but all I get is confusion and this strange image: https://i.sstatic.net/6mvBu.png Does anyone have any insights on what might be causing the issue? HTML <span style="font-weight: 500;">Payload Data: ...

Developing client-side components with NextJS

I want to develop a single-page landing page where users can upload videos and there's a file size limit check before the upload. In my src/app/page.tsx file, I have the following code: import React from 'react'; import FileUpload from &apo ...

The code written inside the <script> tag seems to be malfunctioning when placed in the component.html file within VScode while working with

I'm facing an issue where the script tag for jQuery included in index.html is not being executed within the component.html. There are no errors detected when inspected. Additionally, I have used another script for a toast message box. <script sr ...

Oh no! A critical mistake has occurred: Mark-compact operations are not working efficiently near the heap limit, leading to a failed allocation due to the

My project is not particularly complex, I only just started it. However, when I run the command npm run dev, node js consumes more than 4GB of memory and eventually crashes with a fatal error: --- Last few GCs --- [16804:0000018EB02350F0] 128835 ms: Mar ...

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

The conundrum of Content-Type in Angular 8's HttpClient Post request

Seeking assistance with POST request to backend API! I'm encountering a 415 status code due to the content-type being sent as "text/plain" when the endpoint expects application/json. Interestingly, the POST works in PostMan (see screenshot below). I ...

Availability of variables and declaration of functions

I'm having trouble accessing a variable in my Angular project. I am new to this, so please bear with me. Here's an overview of my project: app.component.html: <div> <ul> <li *ngFor='let var1 of Fcomponent' >{{var1}} ...

Collapsible list in Angular2 sidenav: ensuring only one sublist remains open

Presenting a functional sidenav demo with Angular 2, TypeScript, and Material Design components. The sidenav features a UL, with the Sites and Users anchors expanding to display their own sub-list. Check out the Plunker here Here is the HTML code for the ...

Encountering Angular 8 error TS2304 at line 39: Cannot find the specified name after shutting down WebStorm

After working on my Angular project and closing the IDE last night, I encountered an odd problem today. The project doesn't seem to recognize certain libraries such as Int8Array, Int16Array, Int32Array... And many others. While the project is still ab ...

Different ways to categorize elements of Timeline using typescript

I have some code that generates a timeline view of different stages and their corresponding steps based on an array of stages. Each stage includes its name, step, and status. My goal is to organize these stages by name and then display the steps grouped un ...

Exploring the depths of Angular's nested formGroups

I am facing a challenge in updating my form with data. There is a nested formGroup within another formGroup, and despite receiving the data, the form does not update; it remains empty. The data is visible in the logs, indicating an issue with the form&apos ...

Module 'next-intl/client' cannot be located

When I run npm test, I encounter the following error: 'next-intl/client' module not found jest.mock( | ^ 22 | 'next-intl/client', 23 | (): Record<string, unknown> => ({ 24 | usePathname: ...

What is the process for running an npm package command on a specific subdirectory using PowerShell?

Is there a way to run an npm package command on a specific subdirectory using PowerShell? My situation involves having an ng2 application embedded within a .NET MVC app. The ng2 directory is nested within the main root directory structured as MySite/ng2. ...

Limitation for class instance, not an object

Is it possible to implement type constraints for class instances only in TypeScript, without allowing objects? Here is an example of what I am trying to achieve: class EmptyClass {} class ClassWithConstructorParams { constructor (public name: string) ...

Is it possible to include the term 'public' exclusively within a .ts file in a TypeScript TSLint React environment?

I'm struggling to understand why I am encountering an error in VSCode while working on a react typescript project with tslint setup. The error message states: 'public' can only be used in a .ts file. [Also, I'm wondering why I' ...

Angular Github Deployment Issue: Page malfunctioning as a result of strict-origin-when-cross-origin restriction

I am currently learning Angular and attempting to deploy it on Github Pages. However, I have encountered an issue where the app is not functioning properly. After inspecting the page, I discovered a CORS origin error when trying to access certain resource ...

Tips on implementing pdf-lib in Angular?

I came across the pdf-lib library and am interested in incorporating it into my Angular project. However, I couldn't find any documentation on how to import it specifically for Angular. Can anyone assist me with the process of importing this library ( ...

What is the reason for restricting a placeholder for an optional property in the interface to only be of type any?

I am facing a challenge with a file containing a single declaration, which is for an interface: interface NamedPerson { firstName: string; age?: number; [propName: string]: any; greet(lastName: string): void; } Everything works perfectly ...

Properly implement Angular/Typescript to populate an array with chosen objects

Currently, I have an Angular application that is fetching JSON resources from a Spring Boot REST API. These resources consist of simple player objects with attributes like id, name, position, and value. On the UI, each object is displayed along with a "BUY ...