Angular: Trigger service call upon onBlur event of input changes

In Angular, I am looking to detect any changes in the text input during the onBlur event and then take specific actions accordingly:

Criteria for processing during the onBlur event:

  • Only proceed if there has been a change in the text input.
  • If the input remains unchanged, do not execute any further actions.

For reference, you can view the code with the onBlur event implemented in the following StackBlitz link. However, the console logs even if the input remains the same:

https://stackblitz.com/edit/angular-ngmodelchange-blur-8er79o?file=app/app.component.ts

Answer №1

Here are some steps you can take:

  1. Take note of the current value when the element is focused
  2. Compare the current value to the saved value when the element loses focus
  3. If there's a difference in values, perform the necessary processing
<input (focus)="saveValue()" (blur)="processChange()" [(ngModel)]="someValue" ... />
someValue = "nice";
prevValue = this.someValue;

saveValue() {
  this.prevValue = this.someValue;
}

processChange() {
  if (this.someValue !== this.prevValue) {
    console.log("The value has changed!!!");
    // Additional processing can be done here...
  }
}

Check out a demo on this stackblitz.


If you prefer not to modify the component code, you can save the value as an element attribute:

<input #txt type="text" name="field" 
  (focus)="txt.setAttribute('data-value', someValue)" 
  (blur)="txt.getAttribute('data-value') !== someValue ? processChange() : ''" 
  [(ngModel)]="someValue" />

View a demonstration on this stackblitz.

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 access event.target as an object in Angular 2?

Apologies for my limited English proficiency. . I am trying to write code that will call myFunction() when the user clicks anywhere except on an element with the class .do-not-click-here. Here is the code I have written: document.addEventListener(' ...

Angular 2 destroy outlet-content and refresh the view

Is there a method in Angular 2 to remove a component that was automatically created within a router-outlet? I am looking to destroy it so that a new one is generated when I navigate back to that outlet (or is there a way to reload the outlet?). ...

Performing a HTTP GET request in Angular 2 with custom headers

I recently came across some posts discussing how to set headers in a GET request. The code snippet below demonstrates one way to do this: let headers = new Headers({ 'Accept': 'application/json' }); headers.append('Authorization&a ...

Matching TypeScript against the resulting type of a string literal template

My type declaration looks like this: type To_String<N extends number> = `${N}` I have created a Type that maps the resulting string number as follows: type Remap<Number> = Number extends '0' ? 'is zero' : Number ...

When attempting to navigate to the index page in Angular, I encounter difficulties when using the back button

I recently encountered an issue with my Angular project. On the main index page, I have buttons that direct me to another page. However, when I try to navigate back to the index page by clicking the browser's back button, I only see a white page inste ...

Exploring an Angular Real-World Example Application on Github - Resolving the Following Bug

my surroundings. export const environment = { production: false, api_url: 'localhost:3306/api' }; my personal server is at localhost:3306 (MAMP) The instructions provided are to edit src/environments/environment.ts in order to ch ...

Converting "Observable<any>" to "any[]" in TypeScript: A beginner's guide

Within my Angular application, I am retrieving data from a database using a web API in JSON format. The data is fetched using the following method within my xx-service.ts: //... getMyItem(): Observable<any> { return this.http.get('/api/ ...

Tips for collapsing or expanding a single button in Angular 6

I want to create rows of collapsible buttons in my code, but every time I visit the page, all the buttons are already expanded. Additionally, when I click on any button, they all expand or collapse simultaneously. HTML <div id="accordion" *ngFor="let ...

What could be causing the problem between typescript and Prisma ORM as I attempt to locate a distinct item?

I'm encountering a problem with using the prisma .findUnique() function. Even though my code doesn't display any compilation errors, attempting to access a product page triggers a runtime error. PrismaClientValidationError: Invalid `prisma.produ ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

How can I retrieve the name of a constant enum member in TypeScript as a string?

Consider the following const enum declaration: const enum Snack { Apple = 0, Banana = 1, Orange = 2, Other = 3 } Is it possible in TypeScript to retrieve the string representation of a specific member? In C#, this could be achieved with ...

TypeScript integration for express-validator

Recently, I made an attempt to switch my NodeJS project with ExpressJS to TypeScript for better organization and type safety. However, I encountered an issue with the 'express-validator' middleware during this conversion process. To resolve thi ...

Angular Application Functions Properly on Local Machine, Yet Experiences Issues When Deployed on Azure

I've been making the transition from AngularJS to Angular 2 and beyond. I found a tutorial that helped me set up routing with multiple components using Visual Studio IDE, which worked flawlessly on my local machine: However, when I tried to publish i ...

NG0303: Unable to establish a connection with 'ngbTooltip' as it is not recognized as a valid property of 'button'

ERROR: 'NG0303: Can't bind to 'ngbTooltip' since it isn't a known property of 'button'.' Encountering this issue in my Angular 12 project when running local tests, the ngbTooltip error is present in all .spec files. ...

Utilize Angular to Transfer HTTP Array Data from a Service to a Component

As I work on developing an app with Angular, my current challenge involves a service that retrieves an Array of Data from an online source. My goal is to make this array accessible in other components but I'm facing difficulty in passing the data to t ...

Need for a DatePicker in a dynamic form

I have implemented a reactive form that includes a Datepicker component. <div class="form-group"> <label class="form-control-label" for="field_dataAtivacao">Data Ativação</label> <div class="input-group"> < ...

generating declaration files for components with accurate type definitions from propTypes

I am in the process of creating a react/js library using rollup. My approach involves utilizing typescript to generate declaration files for my components. Despite having propTypes defined for my components, I have noticed that the emitted .d.ts files as ...

Guidelines for converting an array into checkboxes using React Native with TypeScript

As I embark on my React Native journey, I have chosen to use TypeScript in my project. Currently, I am faced with the challenge of mapping an array into a checkbox. Enclosed below is a snippet from my JSON file: { "stud_name": "Adam", "sex": "male" ...

How to eliminate a particular validator from a form group in Angular

My goal is to eliminate the specific validator from the validator array so that I can reconfigure the controls when certain values have changed. I am aware of the traditional solution where I would need to repeatedly set validators. checked(event: MatC ...

The Formly form is experiencing a glitch where it does not reflect the updated default value of

My goal is to dynamically update the Formly form rendering based on changes made in the form scheme (which consists of an array of FormlyFormConfig objects). I have noticed that the updating works when adding a new object or modifying a field label, but it ...