"Techniques for extracting both the previous and current selections from a dropdown menu in Angular 2

How can I retrieve the previous value of a dropdown before selection using the OnChange event?


 <select class="form-control selectpicker selector" name="selectedQuestion1" [ngModel]="selectedQuestion1"   (Onchange)="filterSecurityQuestions($event.target.value,0)">
 <option [value]="0"  disabled selected>Select Secuirty Question1</option>
 <option *ngFor="let securityQuestion of securityQuestions[0]"  [value]="securityQuestion.SecurityQuestionID" >
      {{securityQuestion.Question}}
</option>
 </select>  <br />                       
<div>
<input type="text" class="form-control" id="first_name" name="securityAnswer1" placeholder="Your first security answer">
</div>

filterSecurityQuestions(questionNo: number, securityQtnDropdownNo: number) {
// Need to access previous value of dropdown here. 
}

Answer №1

If you want to maintain the old value of a property, you can create a separate variable to store it as shown in the example below:

HTML

<select #select id="pageSize" [ngModel]="myValue" (ngModelChange)="select.value = onChange($event)"> 
     <option value="1">value1</option> 
     <option value="2">value2</option> 
     <option value="3">value3</option> 
</select> 

Typescript

  myValue = 1;
  oldValue = 1;

  onChange(event) { 
    const response = window.confirm("Are you sure you want change the page size? Your edits will be lost?"); 
    if (response) { 
      this.myValue = event;
      this.oldValue = event;
    }
    else{
      this.myValue = this.oldValue;
    }
    console.log(this.myValue)
    console.log(this.oldValue)
    return this.myValue;
  }

DEMO

Answer №2

Using Ingragistics and other npm libraries can provide these functionalities, however, it is also possible to achieve the same result without relying on external libraries. Take a look at the code snippet below:

perviousSelectedValue: any = null;

onChange(event) {
if(this.previouseSelectedValue == null) {
  // there is no value selected previously. Considering there is no value selected.
  this.previouseSelectedValue = event
  } else {
    console.log('your previousely selected value was: ', this.previousSelectedValue)
  }
}

This solution worked for me and may be useful for others as well. Thank you.

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

Deleting button on Angular 4's CKEditor

Currently, I am utilizing version 4.7.3/basic/ckeditor.js and seeking guidance on how to eliminate the "About" and "NumberedList" buttons. Does anyone have a solution for this? <ckeditor [(ngModel)]="work.points" [config]="{removePlugins: 'Ab ...

Having trouble showing table data in Angular

My goal is to showcase data from a table created using Spring-Boot Below is my model.ts: export class Quiz1 { QuestionId?: any; Question?: string; OptionsA?: string; OptionsB?: string; OptionsC?: string; OptionsD?: string;} He ...

What is the correct way to implement Vue.use() with TypeScript?

I am trying to incorporate the Vuetify plugin into my TypeScript project. The documentation (available at this link) suggests using Vue.use(), but in TypeScript, I encounter the following error: "error TS2345: Argument of type '{}' is not assign ...

Encountering an issue when trying to upload a photo from Angular 8 to Laravel: receiving a "Call to a member function extension() on null" error

In my project using Angular 8 for the front end and Laravel 5.8 for the backend, I encountered an issue with uploading photos. I found guidance in this tutorial from ACADE MIND. Here is my template code : <input *ngIf="photoEdit" enctype="multipart/ ...

Developing an array in Angular on an Android device is proving to be a sluggish

I'm facing an issue with my simple array that collects rows from a database and uses a distance column as a key. let output = {}; for (let dataRow of sqllite.rows) { output[dataRow.distance] = dataRow; } When testing in Chrome browser on my PC, ...

Automatic Formatting of Typescript in SublimeText

Utilizing Microsoft's Typescript Sublime Plugin, I am able to format a file using the shortcut ^T ^F as outlined in the plugin's feature list. Is there a method to automatically execute this command when saving a file? Similar to the functionali ...

There seems to be an issue with executing an imported function from a .ts file within a TSX file in NextJs, resulting

I've encountered an issue that seems to be related to using NextJs with TypeScript. For example: // /pages/index.tsx import _ from 'lodash' export const MyComponent = () => { return ( <ul> { _.map(someArray, ...

Fixing the issue of 'Unrecognized character < in JSON at position 0 at JSON.parse'

I have recently deployed my Angular 6 application on Heroku at . However, upon deploying, I encountered the error message: SyntaxError: Unexpected token < in JSON at position 0 during JSON.parse. I am aware that this error occurs when the response ret ...

Retrieve values from DynamoDB in their original Number or String formats directly

Here is the code I am using to retrieve data from DynamoDB. async fetchData(params: QueryParams) { return await this.docClient.send(new QueryCommand(params)); } const dbObject: QueryParams = { TableName: process.env.TABLE_NAME, KeyCo ...

Encountering a bug in Angular 10 while attempting to assign a value from

I am having trouble updating the role of a user. In my database, I have a user table and a role table with a ManyToMany relation. I can retrieve all the values and even the correct selected value, but I am encountering issues when trying to update it. Her ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...

What is the best way to upload a photo taken with the Android camera using FormData in Ionic/Angular?

Currently in the process of developing an Android app that allows users to capture and upload their picture to a PATCH API endpoint with the key 'avatar'. To accomplish this, I am utilizing the Cordova Camera along with the Advanced HTTP plugin ...

Enhanced assistance for optional chaining operator available in Visual Studio Code

React Native 0.56 now supports the Optional Chaining Operator with ?. Unfortunately, the latest stable version of VS Code does not recognize this syntax and displays a TypeScript validation error: [ts] Expression expected. No compile-time or eslint erro ...

Tips for showing more rows by clicking an icon within an Angular 2 table

When I click on the plus (+) button in the first column of each row, only one row expands. How can I modify it to expand multiple rows at a time? Thanks in advance. <div> <table class="table table-striped table-bordered"> <thead> ...

Utilizing Print Styles in an Angular 7 Application: A Step-by-Step Guide

I'm trying to print an html form within my Angular7 App with minimal margins. I've attempted different solutions such as adjusting the margins manually in Chrome's print preview box and adding @media print styles & @page styles in both the c ...

Best practices for managing backend errors with Next.js 14

Currently, I am developing a project in Next.js 14 and I have set up my API requests using fetch within a handler.tsx file as shown below: async function getPositions() { const response = await fetch( process.env.BASE_API_URL + "/positions?enabl ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

Warning: Angular Compilation Issue - Deprecation Advisory

After upgrading to Angular 13, I've been encountering this deprecation warning. TypeError: message.trim is not a function at Function.Rule.FAILURE_STRING (/home/app/node_modules/tslint/lib/rules/deprecationRule.js:30:81) at cb (/home/app/node_modules ...

The process of ensuring a component is able to watch for the router even when it is not within the router

I am facing an issue with setting v-if for an element to get a boolean value from a function when the router changes the URL. Here is the code snippet for my Header component: <template> <header class="wfm-header"> <div class=" ...

The TypeScript Promise error codes TS2304 and TS2529 are causing confusion among

I came across the code below: function asyncTask(): Promise<string> { return new Promise<string>(resolve => resolve); } This code resulted in the following error: TS2304: cannot find name 'Promise' To address this issue, ...