"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

What is the method to acquire the firestore reference type in TypeScript?

Here is the code I am working with: import { DocumentReference } from '@firebase/firestore-types' export type Recipe = { author: string title: string ingredients: { quantity: number ingredient: DocumentReference["path"] ...

Encountered a 404 error while using a MEAN stack application

Encountering a 404 error while attempting to post data using Postman in Chrome. Any assistance will be greatly valued. I am following the application from this link: https://www.youtube.com/watch?v=wtIvu085uU0 Here is the code snippet: //importing modul ...

Outputting double columns with Typescript Sequelize associations

I am currently in the process of constructing table models using sequelize along with typescript. Here is an example of one of my models: 'use strict'; import { Model, InferAttributes, InferCreationAttributes, CreationOptional } from 'seque ...

Angular Service Worker - Resolving Font Awesome Cross-Origin Resource Sharing

After successfully running our Angular app in production for a year, we recently deployed support for PWA (Progressive Web App) functionality. Everything seemed to be working smoothly until we encountered an issue specific to some Samsung mobile devices. ...

Transforming strings of HTML into objects in the DocX format

After developing a TypeScript script that transforms a JSON string into a Word Doc poster using Docx, I encountered a hurdle. Certain sections of the JSON may contain HTML tags, such as <br/>, <i>, <p>, and I need a way to pass the stri ...

Having trouble accessing the product details in my Angular app hosted on Azure

In Azure, my Angular application is hosted. There's an issue where users cannot open the app by pasting a specific URL into the browser (). Instead of opening, it redirects to , even when pasting . If I try pasting in the browser, it works fine. But ...

Utilize Angular 4 to dynamically load templates within a single component

My task is to create a component with multiple HTML templates, each containing at least 20 controls. Depending on certain conditions, a specific template should be loaded. Note: I have opted for 3 different templates because the controls vary based on the ...

Updates to Providers in the latest release of Angular 2

When working with angular 2.0.0-rc.1, we implemented a Provider using the new Provider method as shown in the code snippet below: var constAccessor = new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => EJDefaultValueAccessor), ...

Fixing errors with observables in an Angular 2 project using Rx

var foo = Observable.create(function(observer){ try{ console.log('hey there'); observer.next(22); throw new Error('not good at all'); setTimeout(function(){ observe ...

Creating an async function in TypeScript to retrieve the coordinates of a particular location is a useful way to streamline the

I am looking to retrieve the coordinates of a location as the output of a function. The coordinates are already assigned within a fetch method, with latitudes stored as coordinates.lat and longitudes stored as coordinates.lng. [Currently, it is returning ...

Exploring the capabilities of Typescript arrays by implementing a forEach loop in conjunction with the

I possess an array: set Array ( [0] => Array ( [name0] => J [name1] => L [name2] => C ) [1] => Array ( [data0] => 3,1,3 [data1] => 5,3 ...

Monitoring User Interactions for Maintaining Session Foresight Plan utilizing RxJS

My goal is to maintain user session activity by implementing a system that locks an interactive session after 15 minutes of user inactivity (defined as no keyboard or mouse activity). The information system will automatically lock the session if there is ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

A guide to creating a TypeScript redux middleware class

As specified in the typescript definition for Redux, these interfaces must be implemented to create middleware: /* middleware */ export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> { dispatch: D getState(): S } /** * A midd ...

What is the process of incorporating a JavaScript node module into TypeScript?

Having trouble importing the xml2js module as I keep getting a 404 error stating that it's not found. import xml2js from 'xml2js'; Any suggestions on how to properly import JavaScript modules located in the node_modules directory when work ...

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

Problem with opening the keyboard feature in an Ionic app

Hello everyone, I'm relatively new to Ionic development and I've been trying to integrate a keyboard plugin into my application that opens from the footer and focuses on input fields for entering values. Here is the link to the plugin I used: ht ...

Can the Angular CLI be installed without using the command prompt?

Are there alternative methods for installing angular cli besides using the command line in cmd? I am encountering proxy setting issues when trying to install it using npm install -g @angular/cli (I am currently using a VPN for work) npm ERR! code ETIMEDOUT ...

Excluding node modules from Webpack TerserPlugin

I am currently working on a custom Angular Builder and I need to exclude an entire module from the minification/optimization process. According to the Webpack .md file: exclude Type: String|RegExp|Array Default: undefined This setting is used to spe ...

The improper utilization or replacement of Jest mock in an Angular standalone component's unit test is causing issues

Presented here is a streamlined Ionic/Angular component with unnecessary code removed. import { IonicModule, ModalController } from '@ionic/angular'; @Component({ selector: 'my-component', templateUrl: 'my-component.html' ...