angular 2: how to reset select list values after submission

Issue

I am encountering a problem where I am not utilizing a form, but rather using the Model values to populate a select list. Upon clicking the submit button, an API is called with the selected model value. However, after the submission, the select list retains the previous values. How can I reset it to display the initial state?

Component

import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { AuthorizeUserDirective } from '../../directives/authorize-user.directive';
import { ProductService } from '../../services/product.service';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../../services/auth/auth.service';
import { PaginatePipe, PaginationControlsCmp, PaginationService, IPaginationInstance } from 'ng2-pagination';
import { LoadingComponent } from '../../../app/components/loading.component';
import { WorkflowComponent } from '../api/workflow.component';
import { ApiService } from '../../services/api.service';
import { ProductModel } from '../../models/product.model';
import { Api } from '../../models/api.model';
import { Scope } from '../../models/scope';
import { Workflow } from '../../models/workflow';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { WorkflowService } from '../../services/workflow.service';
@Component({
    selector: 'product-detail',
    templateUrl: '../../app/components/product/product-detail.html',
    providers: [PaginationService]

})
export class ProductEditComponent implements OnInit {
    @ViewChild('modal')
    modal: ModalComponent;
    api: Api;
    apiDescription: string;
    apiServiceUrl: string;
    wf: Array<Workflow>;;
    sc: Array<Scope>;;
    private isEmpty: boolean = true;
    private apiName: string;
    private isAdmin: Boolean = false;
    private data: ProductModel;
    private id: string;
    isAuthorized: boolean = false;
    private status: string;

    scopeid: number;
    workflowid: number;

    public config: IPaginationInstance = {
        id: 'custom',
        itemsPerPage: 10,
        currentPage: 1
    };
    private response: Observable<any[]>;

    constructor(private router: Router,
        private productService: ProductService,
        private apiService: ApiService,
        private route: ActivatedRoute,
        private authService: AuthService) {

        this.route.params.subscribe(params => {
            this.id = params['id'];
        });
        this.status = 'loading';
    }

    ngOnInit() {

        this.productService.getProductById(this.id);
        this.data = this.productService.singleProduct;
        this.productService.getAllWorkflow()
            .subscribe(data => this.wf = data);

        this.productService.getAllScope()
            .subscribe(data => this.sc = data);

        this.status = 'active';
        if (this.data.Apis.length > 0) {
            this.isEmpty = false;
        }
    }

    save(api) {

        this.apiService.saveApi(api,this.scopeid, this.workflowid)
            .subscribe(data => {
                this.response = data;
            },
            error => {
                console.log("error while saving scope and workflow");
            });
    }

    getApi(apiId) {
        this.productService.getApiById(apiId);
        this.api = this.productService.api;
        this.apiName = this.productService.api.Name;
        this.apiDescription = this.productService.api.Description;
        this.apiServiceUrl = this.productService.api.ServiceUrl;
        this.modal.open();
    }

    onChangeworkflow(deviceValue) {
        this.workflowid = deviceValue;
    }
    onChangeScope(deviceValue1) {
        this.scopeid = deviceValue1;
    }
}

HTML

 <modal #modal>
            <modal-header [show-close]="true">
                <h4 class="modal-title">{{apiName}}</h4>
            </modal-header>
            <modal-body>
                <div class="row">
                    <div class="col-md-12">
                        <!-- Reg-Form -->
                        <div id="sky-form4" class="sky-form" style="border:0px;">
                            <div class="row" *ngIf="apiServiceUrl">
                                <section class="col-xs-3">
                                    <label>
                                        URL : 
                                    </label>
                                </section>

                                <section class="col-xs-9">
                                    <label>
                                        {{apiServiceUrl}}
                                    </label>
                                </section>
                            </div>
                            <div class="row" *ngIf="apiDescription">
                                
                                <section class="col-xs-3">
                                    <label>
                                        Description : 
                                    </label>
                                </section>

                                <section class="col-xs-9">
                                    <label>
                                        {{apiDescription}}
                                    </label>
                                </section>
                            </div>
                                <section>
                                    <label class="select" (change)="onChangeworkflow($event.target.value)">
                                        <select>
                                            <option *ngFor="let w of wf" [value]="w.Id">{{w.Name}}</option>
                                        </select>
                                        <i></i>
                                    </label>
                                </section>


                                <section>
                                    <label class="select" (change)="onChangeScope($event.target.value)">
                                        <select>
                                            <option *ngFor="let s of sc" [value]="s.Id">{{s.ScopeName}}</option>
                                        </select>
                                        <i></i>
                                    </label>
                                </section>


                            </div>
                        <!-- End Reg-Form -->
                    </div>

                </div>
                <api-workflow></api-workflow>
            </modal-body>
            <modal-footer>
                <button type="button" class="btn-u btn-u-default" data-dismiss="modal" style="margin-right:5px;" (click)="modal.dismiss();">Close</button>
                <button type="submit" class="btn-u pull-right" (click)="save(api)" data-dismiss="modal">Save</button>
            </modal-footer>
        </modal>

Answer №1

Upon starting, create a duplicate of the starting parameters.

Following submission, refresh the data models using the duplicated values.

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

Creating Dynamic Graphs using Angular and Chart.js with Array Values

I have implemented ChartJS-2 to visualize a graph displaying an array of user activities, but it appears distorted: import { Component, OnInit, Input } from '@angular/core'; import { ChartOptions, ChartType, ChartDataSets } from 'chart.js ...

The encryption and decryption feature is not functioning properly within the client-server application

We are currently experiencing issues with the encryption-decryption of data. On the server-side, we have decryption Java code that looks like this: public static String decrypt(byte[] data, PrivateKey base64PrivateKey) throws NoSuchPaddingException, NoSuc ...

What are the steps to fix the error stating that 'loginError.data' is an unknown type?

Recently delving into typescript, I decided to test the waters with nextjs, rtk query, and antd. However, while attempting to access error within useLoginMutation using the property error.data.message, it was flagged as type unknown. To tackle this issue, ...

Error occurred after attempting to make a GET request

What I aim to achieve: I need to send two parameters from the front-end to the back-end. This is the code snippet: In TypeScript file: activeFromActiveToQuery(req?: any): Observable<ResponseWrapper>{ const options = createRequestOption(req) ...

Displaying maximum number of items in each row using ngFor

Is there a way to automatically create a new row within the 'td' element after the ngFor directive has generated 10 image repeats? Currently, all the images are displayed in a single td and as more images are added, they start to shrink. <td ...

Can an Angular 5 web application be developed without using Node.js/npm?

I want to develop an Angular 5 web application using Java, but my boss prefers not to use Node.js/npm. Is it possible to build an app without Node.js/npm and rely solely on Java? Most of the resources I've come across recommend using Node.js/npm, inc ...

What are the steps to testing an endpoint with Jasmine/Karma?

Within one of my components, there is a method that makes a call to an endpoint in the following manner... private async getRolesAsync(): Promise<void> { const roles = await this.http.get<any>('https://sample-endpoint.com').toProm ...

Attempting to launch an Angular web application on Azure's Linux-based Web App service

Currently, I am in the process of deploying my angular web app onto a free tier azure web app service for testing purposes. The deployment itself is done using an Azure pipeline and seems to be successful according to the logs found in the Deployment Cente ...

Angular Custom Validator Error (Validation function must either return a Promise or an Observable)

I created a personalized validator for the phone field but I'm encountering an issue The validator should be returning either a Promise or an Observable. Basically, I just want to check if the phone number is less than 10 characters. HTML Cod ...

Generate a new data structure by pairing keys with corresponding values from an existing

Imagine having a type named Foo type Foo = { a: string; b: number; c: boolean; } Now, I am looking to create a type for an object containing a key and a value of a designated type T. The goal is for the value's type to be automatically determin ...

When utilizing <number | null> or <number | undefined> within computed() or signals(), it may not function properly if the value is 0

I've encountered an issue while implementing signals and computed in my new Angular project. There's a computed value that holds an id, which is initially not set and will be assigned by user interaction. To handle this initial state, I attempte ...

using angular and firestore to grant public reading permission for a document

As a student developer, I recently integrated Firestore into my Angular app and encountered some challenges with the security rules. My goal: I want to display a Firestore document in an Angular view using template binding. The document should be visible ...

Is it appropriate to use a component inside an entry component?

I'm currently working on a component that triggers a function to open a window: @Component({ selector: 'app-deposits', templateUrl: './deposits.component.html', styleUrls: ['./deposits.component.scss&apo ...

"Hmm, the React context's state doesn't seem to be changing

I have been working on a next.js app and I encountered an issue related to using react context to export a state. Despite my efforts, the state doesn't seem to update and it remains stuck at the initial value defined by the createContext hook, which i ...

Experiencing CORS problem in Ionic 3 when accessing API on device

I am a newcomer to IONIC and I am utilizing a slim REST API with Ionic 3. Currently, I am encountering the following error: "Failed to load : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin&apos ...

Struggling to retrieve object values through useContext? Consider implementing useReducer in conjunction with useContext for more efficient state management

I'm facing an issue while trying to access my dispatch functions and states from the useContext. Strangely, when I attempt to destructure the context object in order to access them directly, I receive an error message stating that it does not exist (E ...

The File Filter feature of Angular's ng2-file-upload is not functioning correctly for PNG files in the Internet Explorer

I am encountering an issue with the file uploader plugin ng2-file-upload when trying to upload a PNG file using Internet Explorer 11. For some reason, the PNG files are not being added to the queue, even though all other allowed file types work perfectly f ...

Issue with loading CSS in Angular 8 upon refreshing the page after building in production

Here is the structure of my index.html: <!doctype html> <html lang="hu"> <head> <meta charset="utf-8"> <title>WebsiteName</title> <base href="/"> <meta name="viewport& ...

Tips for ensuring that jQuery runs in the correct order within Angular 2

As a beginner with Angular 2 and asynchronous loading, I have encountered some difficulties in finding the right approach for running jQuery scripts in the correct sequence within an Angular 2 project. Despite exploring various resources such as: How to u ...

Implement the agmCircle method from angular-google-maps in a typescript file

Is there a way to retrieve the bounds of a circle once it has been changed? I noticed on that there is a "getBounds" method available. How can I access this method from my typescript file in order to log this data? This is how my html circle component cur ...