Clear drop down selections after button is pressed

I am currently working with a grid in my template that contains multiple dropdowns, each row having its own. When I click a button, I gather the values from these dropdowns. However, upon clicking this button, I wish to reset all the dropdowns back to their default values.

<div>
    <button (click)="onClickUpdate($event, filteredRequesters)">Update</button>
</div>
<tbody>
    <tr *ngFor='let requester of filteredRequesters'>
        <td>
          <select id="ddStatus" type="number" (change)="onChange($event.target.value, requester)">
             <option *ngFor="let level of levels">
    {{level.name}}</option>
          </select>
        </td>
        <td>{{ requester.RequesterID }}</td>
        <td> {{ requester.FullName }} </td>
        <td>{{ requester.CompanyName }}</td>
        <td>{{ requester.RequesterClass}}</td>
        <td>{{ requester.Address}}</td>
        <td>{{ requester.MobilePhone}}</td>
        <td>{{ requester.TotalRequests}}</td>
        <td>{{ requester.EmailAddress}}</td>
    </tr>
</tbody>

Below is the array responsible for populating the options within the select dropdown in the corresponding typescript component.

   levels: Array<{ num: number, name: string, total: number }> = [
    { num: 0, name: "ignore", total: 0 },
    { num: 1, name: "child", total: 0 },
    { num: 2, name: "parent", total: 0 }
   ];

Lastly, here is the code that executes upon clicking the button:

 onClickUpdate(event, filteredRequesters) {

    var count: number;
    count = 0;

    for (var i = filteredRequesters.length - 1; i >= 0; i--) {
        if (count > 1) {
            continue;
        }

        if (filteredRequesters[i].isDisabled == 2)
            count++
    }

    if (count == 1) {
        this._productService.updateRequester(filteredRequesters);
        var countToRemove: number;
        // get new total requests for merged reqwester  
        var countIndex: number = 0;
        countToRemove = 0;
        for (var i = filteredRequesters.length - 1; i >= 0; i--)
            if (filteredRequesters[i].isDisabled == 1) {
                countToRemove += filteredRequesters[i].TotalRequests;
            }
            else if (filteredRequesters[i].isDisabled == 2)
                countIndex = i;

        filteredRequesters[countIndex].TotalRequests += countToRemove;
        filteredRequesters[countIndex].isDisabled = 0;

        for (var i = filteredRequesters.length - 1; i >= 0; i--)
            if (filteredRequesters[i].isDisabled == 1)
                filteredRequesters.splice(i, 1);
                // this._productService.getRequestersByFirsterLetter('a')
                // .subscribe(products => {
                //     this.products = products;
                //     this.filteredRequesters = this.products;
                // },
                // error => this.errorMessage = <any>error);
    }
    else alert("Only one parent allowed. ")       
}

Answer №1

If you choose not to include a form, you can still utilize ngModel in the select element to bind its value to a property and easily reset it without the need for manual retrieval or changes. Here is an example of how you can implement this:

<select id="ddStatus"  [(ngModel)]="selectedValues[i]" type="number">

In this code snippet, selectedValues represents the property that the select element is bound to. You can then reset its values effortlessly using the following method:

reset(){
      this.selectedValues=["ignore","ignore","ignore"];
  }

Simply call this.reset() from the button click event.

Check out a simplified demo for reference.

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

Ways to address observables in Angular in a manner similar to deferred objects

Transitioning from AngularJS to Angular has posed a challenge for me, especially when it comes to moving from promises to observables. Below is an example of my code in AngularJS: var deferred = $q.defer(), frame = document.createElement('newFrame ...

Extending the Object prototype within an ES6 module can lead to errors such as "Property not found on type 'Object'."

There are two modules in my project - mod1.ts and mod2.ts. //mod1.ts import {Test} from "./mod2"; //LINE X interface Object { GetFooAsString(): string; } Object.prototype.GetFooAsString = function () { return this.GetFoo().toString(); } //mod2. ...

Having trouble accessing undefined properties? Facing issues with the latest Angular version?

Why am I encountering an error and what steps can be taken to resolve it? Currently using the latest version of Angular. ERROR TypeError: Cannot read properties of undefined (reading 'id') Here is the JSON data: { "settings": [ { ...

The date displayed in the table is incorrectly showing 04 instead of 03 when using the pipe

{{element.createdAt | date: 'MM/dd/yyyy h:mm'}} why are the dates in the database all showing as 23 but some values are displaying as 24? Please confirm. The first two values created in the db show a createdAt time of 3, but the table is showing ...

Retrieving JSON data in Angular 5 returns a 400 bad request error

Having trouble calling the REST API of Amazon S3 from Angular 5. Keep getting a 400 bad request error. This problem has been persisting for a while now and I really need to find a solution or at least get some suggestions on where the issue might be. Her ...

"I am looking to retrieve the properties of an object that belongs to the EChartsOption type in TypeScript when working with Angular and ECharts. How

Currently, I am exploring how to access a property of an EChartOptions object in Angular 16.0.2, which may be undefined as I am still new to TypeScript. List of npm packages: eapp/src$ npm list <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Unveiling the Power of Angular 4's HttpClient for Eff

I have encountered an issue with my API, where it returns ISO date that I need to convert into a JavaScript date. Despite using the HTTPClient module for automatic mapping, the data received is not being transformed as expected. While I am aware that it c ...

Require that the parent FormGroup is marked as invalid unless all nested FormGroups are deemed valid - Implementing a custom

Currently, I am working on an Angular 7 project that involves dynamically generating forms. The structure consists of a parent FormGroup with nested FormGroups of different types. My goal is to have the parentForm marked as invalid until all of the nested ...

The use of Next.js v12 middleware is incompatible with both node-fetch and axios

I am facing an issue while developing a middleware that fetches user data from an external endpoint using Axios. Surprisingly, Axios is not functioning properly within the middleware. Below is the error message I encountered when using node-fetch: Module b ...

"Upon receiving a request in Net Core 6 + Angular, null properties are detected in the

Greetings! I am currently working on a project using .NET Core 6 with Angular 12. Within my project, I have a login controller along with its corresponding request model. Interestingly, when I execute the request through Swagger or Postman, everything wo ...

Error: Please note that the loading of the style/types.scss file in the dist build

I am facing an issue with including a general style/types.scss file in the dist folder. Despite having what seems to be correct rules, I cannot locate the content of the file in the build output. What steps can I take to debug this problem and investigate ...

Combining TypeScript and ReactJS with RequireJS: A guide to importing react-dom in TypeScript

I am currently working with TypeScript and React.js. Within Visual Studio 2015, I have set the project properties to use AMD as the module system for TypeScript build, meaning I am utilizing requirejs for importing modules. Within my main.tsx file, I am r ...

Troubleshooting Clarifai object error while invoking "model.predict" within Angular Framework

I've been attempting to utilize Clarifai's color API to extract the different colors present in an image. Unfortunately, I am encountering challenges when trying to call the API, as it consistently returns empty objects. Below is the snippet of ...

Utilizing handpicked information in Angular: A beginner's guide

Being new to Angular and programming in general, I am currently navigating through the intricacies of Angular and could use some guidance on utilizing selected data. For instance, I would like to use a personnel number view image here and send it to the b ...

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...

Access the Angular directive instance before it is actually rendered

Is it possible to access an Angular directive instance even if it has not been rendered yet? Let's say I have an app-component and a baz-directive. I want to be able to get the directive instance even if it is not currently shown or rendered in the D ...

React encountered an issue: each child element within a list must be assigned a unique "key" prop

I am feeling a bit puzzled as to why I keep getting the error message: child in a list should have a unique "key" prop. In my SearchFilterCategory component, I have made sure to add a key for each list item using a unique id. Can you help me figu ...

How to declare and initialize a variable in Angular 2 using TypeScript

I'm currently working with angular 2 and I'm having trouble understanding how to set a variable. The variable _isLoading is being set in "this.observable.filter((event)" but it doesn't seem to change in the template. This is my TypeScript co ...

Create a TypeScript declaration file for a JavaScript dependency that contains an exported function

I am currently utilizing a dependency called is-class in my TypeScript project. Unfortunately, this particular dependency does not come with a @types definition. As a workaround, I have been using a custom .d.ts file with declare module 'is-class&apos ...

Ways to enhance focus on childNodes using Javascript

I am currently working on implementing a navigation system using a UL HTML Element. Here's the code I have so far: let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name); if (arg.keyCode == 40) { // down a ...