Extracting deleted characters from input in Angular 2

Is there a way to detect a removed character from a text using ngModel in Angular 2?

I am looking for something like:

Original text: @Hello World !

Modified text: Hello World !

Console.log

Removed character: '@'

I came across an interesting example in Javascript using Jquery by Arie Xiao at the link below:

However, I am curious if there is an alternative to using Jquery as I have found it challenging to implement in Angular 2.

Answer №1

To respond to changes in the input field, I recommend using a Forms controller. The code snippet highlights the characters added or removed from the input field. Feel free to visit my Plunker to see the code in action.

@Component({
  selector: 'app-root',
  template: `
    <input type="text" [formControl]="form"  class="form-control" >
    <h3 *ngIf="initial">
      Text <span [style.color]="textadd ? 'green' : 'red'" > {{textadd ? "add" : "removed" }} </span>: {{change}}
    </h3>
  `,
})
export class App {
  form;
  textadd;
  text = "@Hello World!";
  initial = false;
  change;
  ngOnInit() {
    this.form = new FormControl({ value: this.text, disabled: false });

    this.form.valueChanges.subscribe(val => {
      let change;
      if (val.length > this.text.length) {
        change = val;
        for (let variable of this.text) {
          change = change.replace(variable, '');
          this.textadd = true;
        }
      } else {
        change = this.text;
        for (let variable of val) {
          change = change.replace(variable, '');
          this.textadd = false;
        }
      }
      this.change = change;
      this.text = val;
      this.initial = true;
    });
  }
}

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

How to Effortlessly Populate Cascading Dropdowns in ASP.Net MVC 5 using a Reusable

I am currently working on an ASP.Net MVC 5 application that has multiple edit pages. Each edit page consists of various input elements such as textboxes, checkboxes, and dropdowns. I want to implement a functionality where the values of one dropdown are ch ...

Can :[Interface] be considered a correct array declaration in Typescript?

My TypeScript codebase is filled with code snippets like the one below... export interface SomeType { name: string; } export interface SomeComposedType { things: [SomeType]; } Everything was working smoothly until I started experiencing issues su ...

Saving data from Material UI forms in TypeScript

Is there an effective method for storing values entered into the text fields on this page? const AddUserPage = () => ( <div> <PermanentDrawerLeft></PermanentDrawerLeft> <div className='main-content'> < ...

AngularJS uses double curly braces, also known as Mustache notation, to display

I'm currently working on a project where I need to display an unordered list populated from a JSON endpoint. Although I am able to fetch the dictionary correctly from the endpoint, I seem to be facing issues with mustache notation as it's renderi ...

What methods can I use to streamline integration with minimal lines of code?

Seeking help with JavaScript: Recently dived into JavaScript and managed to create the desired functionality for my navigation menu. However, I suspect that my code is not optimized as I find myself repeating lines unnecessarily. Here's a snippet of ...

What is the best way to convert an array of data into a dataset format in React Native?

Within my specific use case, I am seeking to reform the array structure prior to loading it into a line chart. In this context, the props received are as follows: const data = [26.727, 26.952, 12.132, 25.933, 12.151, 28.492, 12.134, 26.191] The objective ...

The troubleshooting of a find method in Mongoose

Why is it necessary to use await twice when calling the model function, even though we already used await in the model itself: async function model() { return await data.find({}, '-_id -__v') } When I console.log await data.find({}, '-_id ...

Differences between referencing and valuing in arrays in JavaScript

I have noticed an interesting behavior when passing arrays to functions by reference. Even after modifying the array inside a function, the changes do not reflect when logging the array outside the function. For example: let arr = [1, 2]; console.log(arr ...

Is the required attribute for form submission in Material UI not verifying in another file?

It seems that I may be importing incorrectly because a required field does not display a "please fill in this field" popover when attempting to submit a form. The imported classes are as follows: import * as React from 'react' import FormContro ...

Combining a table to create a JSON object with an array attribute

I am currently working with two SQL tables that have a one-to-many relationship. The query for this data is being requested by my node.JS server and I need to parse the information into a specific JSON format. For each repeated row, I want to insert the da ...

At what point are DOMs erased from memory?

Recently, I've been working on an application that involves continuous creation and removal of DOM elements. One thing I noticed is that the process memory for the browser tab keeps increasing even though the javascript heap memory remains steady. To ...

Exploring Function Overriding in TypeScript

Currently, I'm working on developing a TypeScript method. import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ p ...

Choose images at random from an array within a React Native application

I've been working on a feature that involves randomly selecting an image from an array of images. However, I keep running into the issue of getting an "invalid props source supplied to image" error. My goal is to display a different random image each ...

Refreshing the Angular2 view upon asynchronous model changes

Looking at my Angular2 component, I see that it has a dependency on a datastore. In the template, there are some data bindings connected to that store, like "{{datastore.weather.curTemp}}". The datastore receives updates periodically through http requests. ...

The problem of removing issue divs persists despite Jquery's efforts

Just yesterday, I successfully created a Commentbox using PHP, HTML, and ajax. The beauty of the ajax part is that it allows me to delete a comment without having to refresh the page. To achieve this, I assign a unique id to each comment (div) through the ...

Ways to verify the HTTP 200 status code in Angular when it's not present in the JSON reply

Authentication Service logout() { return this.http.post(this.logOutApi, null); } While the status code does not appear in the JSON response from the backend, it does show on Postman's status. How can the status code be retrieved? Typescr ...

Converting a ReadStream to a ReadableStream in NodeJS: A Step-by-Step Guide

This question poses the opposite scenario to converting a ReadableStream into a ReadStream. ReadStream is a data structure utilized in Node.js ReadableStream is a structure that comes from the web platform, as detailed here As new runtimes like Deno or t ...

Is there a way to ensure that both new Date() and new Date("yyyy-mm-dd hh:mm:ss") are initialized with the same timezone?

When utilizing both constructors, I noticed that they generate with different timezones. Ideally, they should be in the same timezone to ensure accurate calculations between them. I attempted to manually parse today's date and time, but this feels li ...

Ways to link information from one entity to another

Currently, I am utilizing the TMDB API to showcase movies along with their respective genres. In my code, I have two objects where I retrieve details for movies and genres as shown below: listTrendingMovies() { this.listMediaService.listTrendingMovie ...

How to retrieve the image source from a block using jQuery

Currently, I am working on developing a slider for my webpage using jquery's "Cycle" plugin. However, I have encountered an issue with accessing the image sources used in the slider. To provide more context, here is a snippet of code from the 'he ...