Angular - Clear the selection of <select><option> if I opt out of accepting the change

I have created a dropdown menu using HTML <select> and <option> tags, along with a JavaScript function that triggers a confirmation dialogue when an option is selected. The confirmation offers a simple choice between "yes" or "no."

If the user selects "yes," the current state will be updated to the chosen option from the dropdown. Choosing "no" will keep the state unchanged.

The issue I am facing is that after selecting "no," the dropdown menu remains highlighting the option that was rejected. Is there a way for the dropdown menu to revert back to showing the current state instead?

Here is a link to my StackBlitz project demonstrating the problem

UPDATE

While some of the responses provided useful insights, one aspect that was not addressed is that the state does not display the disabled option if it does not have an assigned value.

Answer №1

Save the previously selected option in a variable called preState and revert to this value when the user clicks "no".

export class AppComponent  {
  state;
  newState;
  preState;
  checkState = false;

  options = [
    {name:'dormant'}, 
    {name:'active'}, 
    {name:'finished'}
  ];

  setState(state) {
    this.preState = this.newState;
    this.newState = state
    this.checkState = true;
  }

  selectedOption(option) {
    return this.newState === option;
  }

  yes() {
    this.state = this.newState;
    this.checkState = false;
  }

  no() {
    this.checkState = false;
    this.newState = this.preState;
  }
}


UPDATE:

To display the disabled option mentioned in your update, add [selected]='!newState' on the disabled option:

<select (change)="setState($event.target.value)">
  <option disabled [selected]='!newState'>--Select an option--</option>
  <option *ngFor="let option of options" [value]="option.name" [selected]="selectedOption(option.name)">{{option.name}}</option>
</select>

<div *ngIf="checkState" class="check-state">
  <p>Are you sure you want to change</p>
  <p><span class="bold">{{state}}</span> to <span class="bold">{{newState}}</span></p>
  <button (click)="yes()">yes</button><button (click)="no()">no</button>
</div>

Answer №2

Upgrade to reactive forms and initialize the default state.

You can then utilize the reset method on your form control using the default state.

Explore Stackblitz Example

<select [formControl]="selection">
  <option disabled>--Choose an option--</option>
  <option *ngFor="let choice of choices" [value]="choice.name" [selected]="chosenOption(choice.name)">{{choice.name}}</option>
</select>
selection: FormControl = new FormControl(this.choices[0].name);
defaultState = this.selection.value;

constructor() {
  this.selection.valueChanges.subscribe(value => this.updateState(value));
}

...

resetForm() {
  this.selection.reset(this.defaultState);
  this.reviewState = false;
}

Important Note: I demonstrated using a form control, but the same concept applies to form groups as well

Answer №3

If you're not using two-way binding, any changes to your variable won't impact the template. Here's a suggested approach:

HTML file

<select [(ngModel)]="state" (change)="setState()">
  <option disabled [value]="null">--Choose an option--</option>
  <option *ngFor="let option of options" [value]="option.name" >{{option.name}}</option>
</select>

<div *ngIf="checkState" class="check-state">
    <p>Are you sure you want to make this change?</p>
    <p><span class="bold">{{lastState}}</span> will be changed to <span class="bold">{{state}}</span></p>
    <button (click)="yes()">Yes</button><button (click)="no()">No</button>
</div>

TS File

state;
lastState;
checkState = false;

options = [
  {name:'dormant'}, 
  {name:'active'}, 
  {name:'finished'}
];

constructor() {
  this.lastState = this.state;    
}

setState() {
  this.checkState = true;
}

yes() {
  this.checkState = false;
  this.lastState = this.state;    
}

no() {
  this.checkState = false;
  this.state = this.lastState;
}

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 process for sending Raw Commands to a Receipt Printer using Node.JS?

My Current Project I am currently working on integrating a receipt printer that supports ESC/P raw printing into an app for remote printing of receipts. The Approach I Am Taking To achieve this, I am utilizing the PrintNodes API to send data from my app ...

What is the process for making changes to a document in Mongoose?

My goal is to allow users to update existing mongoose documents using a form with method-override package. Despite trying various solutions found on Stackoverflow, I have not been able to resolve my issue. The desired functionality is for the user to view ...

How to efficiently store and manage a many-to-many relationship in PostgreSQL with TypeORM

I have a products entity defined as follows: @Entity('products') export class productsEntity extends BaseEntity{ @PrimaryGeneratedColumn() id: number; //..columns @ManyToMany( type => Categories, categoryEntity => cat ...

How can I populate a form in Meteor with data from a MongoDB collection that was previously inserted?

Recently, I completed constructing a lengthy form field where users can enter a plethora of information. This form consists of various text and number fields, radio button sets, and checkbox groups. The data is successfully saved in a Mongo collection with ...

Converting data received from the server into a typescript type within an Angular Service

Received an array of Event type from the server. public int Id { get; set; } public string Name { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } For Angular and TypeScript, I need to transform it into the following clas ...

I am encountering an issue where I am using Getserversideprops within a page to retrieve data from Strapi, but I am consistently

Having an issue with fetching data from a Strapi backend using getServerSideProps in Next.js. The data appears to be undefined, even though the link works correctly in the browser. I am fetching inside a page, not a component, following the method descri ...

Set a dynamic Active Class on various divisions by utilizing their respective indexes

I have two divs with the same class. When I click on an anchor tag within one of the elements, I want to add a class to the corresponding position in the second div as well. Mirror: JSFiddle Here is the jQuery code snippet: $(document).on('click ...

Passport JS receiving negative request

I'm currently experiencing an issue with the passport req.login function. When a user logs in using their email and password, instead of redirecting to /productos2 as intended, it routes to a bad request page. I am utilizing ejs and mongoose for this ...

Is it possible for the outcome of a component to be passed to render and actually show up as undefined

I am currently working on creating a wrapper component for an API call in order to display "loading" if the API hasn't updated yet. As I am new to React, I am struggling with passing the state to the ApiResp component: After checking the console.log ...

Issue with loading Three.js asynchronously

My attempt to determine the maximum value of a point cloud data using the following code proved unsuccessful. import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader"; let max_x = -Infinity; function initModel() { new PLYLoader().load ...

Using NavParams within a service component,

I'm facing a challenge in accessing NavParams within a provider, and simply importing NavParams is not solving the issue. Here's a brief overview of my application: users input their name and address, a pin is dropped on the map based on the add ...

A child component in Vue.js unexpectedly starts updating when the parent component renders and uses object literals as props

I'm currently facing an issue with my Vue components where object literals are passed as props like: <child :prop1="{ foo: 'bar' }"></child> After rerendering the parent component, the prop prop1 changes and triggers an update ...

Using Angular's ng-switch directive within a select dropdown option

Can we implement the [Data Presentation Format] to be utilized in the [Dropdown Box]? Specifically, I would like the "parent" items to appear as is within the dropdown, while the "child" items should have a [tab] indentation to denote their relationship wi ...

Switching the website address after picking an option from the drop-down menu

I have an HTML form that includes two dropdown menus. The first dropdown is populated from a database using PHP, and the second dropdown is linked to the first one and uses AJAX to update its values based on the selection from the first dropdown. My goal ...

Tips for simulating the getCustomRepository function in typeORM

I am facing a challenge in unit-testing a class that has a getCustomRepository method in its constructor. I'm struggling to find an easy way to mock it. Below is the code for my class: import {getCustomRepository} from 'typeorm'; export cl ...

Is it possible to rearrange the slide order in Swiper Grid View?

<swiper-container class="mySwiper" slides-per-view="3" grid-rows="2" grid-fill="row" [navigation]="false" space-between="30"> <swiper-slide *ngFor="let item of lists;"& ...

Does performing regForm.reset() not only clear the form but also deactivate it?

When I use .reset() to reset my form, it works as expected. However, after resetting, when I try to type in the input fields again nothing happens and they don't accept any inputs. <form (ngSubmit)="onFormSubmit(regForm)" #regForm="ngForm"> ...

Create text that alternates between blinking and changing content simultaneously

I'm currently working on a website and I am curious about how to achieve the effect of making text blink and change content simultaneously, similar to what is seen on this particular website . Sorry for not being more specific in my question. Thank yo ...

How to troubleshoot Javascript code that fails to identify if a color is white

What could be causing my code to malfunction? I am attempting to determine if the paragraph text color is white (as determined by CSS settings). If it is indeed white, I want to change it to black for better visibility. function adjustColor() { if (d ...

The program is unable to locate the script files I have saved

Currently, I am utilizing node.js alongside express and AngularJS to construct my website. However, I am encountering an issue in the console output where the program seems unable to locate my script files. GET http://localhost:3000/images/entet_gauche.gi ...