Ways to verify if a function has completed execution and proceed to invoke another function

I am seeking to verify if a user has chosen an item from the ngFor form and then redirect them to another page upon submitting the form with the updated value.

HTML:

<mat-select placeholder="Treatment" [(ngModel)]="model.TreatmentA" name="TreatmentA" #TreatmentA (change)="onChange(TreatmentA.value)"
 disableRipple>
    <mat-option value="Sutent (Sunitinibum) 25mg">Sutent (Sunitinibum) 25mg</mat-option>
    <mat-option value="Sutent (Sunitinibum) 37.5mg">Sutent (Sunitinibum) 37.5mg</mat-option>
    <mat-option value="Sutent (Sunitinibum) 50mg">Sutent (Sunitinibum) 50mg</mat-option>
</mat-select>

<div class="row">
            <button mat-raised-button color="primary" type="submit" value="submit">Update Patient</button>
            <button mat-raised-button color="accent" (click)="goBack()">Cancel</button>
          </div>

TS

private onChange(TreatmentAValue): any {
    console.log(TreatmentAValue);
}

onChangeSubmit(){
    const CONDITION = true;
    const DATA = this.onChange(this.TreatmentAValue);
    const ERROR = new Error(this.goBack())

    const promise =
        new Promise((resolve, reject) => {
            // do some async stuff
            this.router.navigate(['/patient/ra', this.id]);

            if (CONDITION) resolve(DATA);
            else reject(ERROR);
        })

    updatePatient() {
        this.patientService
            .updatePatient(this.model)
            .subscribe(() => this.onChangeSubmit());

    }
  model = new Patient();
  id = this.route.snapshot.params['id'];
  private getSinglePatient(): any {
    this.patientService
        .getPatient(this.id)
        .subscribe(patient => {
          this.model = patient[0];
        })
  }
    }

In summary, I need to confirm if a selected treatment value has changed for a specific field, and then direct the user to the desired component only if they have selected a new treatment from the list when submitting the form...

Answer №1

To ensure your original and changed values are stored separately, you can create distinct variables for each like so:

originalTreatment: any;
newTreatment: any;

Then, in your onChange() method, assign the new value as shown below:

private onChange(newTreatmentValue): any {
    this.newTreatment = newTreatmentValue;
}

Finally, to compare the values and check for differences, you can do the following:

onChangeSubmit(){
    const DIFFERENCE = this.originalTreatment !== this.newTreatment;
    const CHANGES = this.onChange(this.newTreatment);
    const ISSUE = new Error(this.goBack());

    const promise =
        new Promise((resolve, reject) => {
            // perform asynchronous operations
            this.router.navigate(['/patient/treatment', this.id]);

            if (DIFFERENCE) resolve(CHANGES);
            else reject(ISSUE);
        });

    updatePatient() {
        this.patientService
            .updatePatient(this.model)
            .subscribe(() => this.onChangeSubmit());
    }
}

If needed, feel free to adjust the code based on your specific data structures.

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

Pass the API_BASE_URL parameter from the Angular 7 configuration

Currently, I am developing an Angular 7 Application using es6 Javascript and Swagger integration. My current challenge involves adding the configuration to APP_INITIALIZER in the app.module file: export class SettingsProvider { private config: AppConfi ...

Utilizing Next.js to Import a Function from a Path Stored within an Environment Variable

I'm having trouble importing a function whose path is stored in an environment variable Current import statement: import { debug } from '../lib/site-A/utils' Expected import statement: import { debug } from process.env.DEBUG_PATH In my ...

Steps for Adding a JS file to Ionic 3

I'm trying to figure out how to access a variable from an external JS file that I included in the assets/data folder. Here's what I've attempted: I placed test.js in the assets/data folder. In test.js, I added a variable testvar = "hello ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

Typescript is throwing a fit over namespaces

My development environment consists of node v6.8.0, TypeScript v2.0.3, gulp v3.9.1, and gulp-typescript v3.0.2. However, I encounter an error when building with gulp. Below is the code snippet that is causing the issue: /// <reference path="../_all.d. ...

The production build of Angular 2 with special effects amplification

I am currently working on an Angular 2 Beta 8 app that I need to bundle and minify for production deployment. Despite configuring the system to generate a Single File eXecutable (SFX) bundle, I am encountering issues with creating a minified version of the ...

Enabling the "allowUnreachableCode" Compiler Option in Visual Studio 2015 Triggers "JsErrorScriptException (0x3001)" Issue

We've implemented TypeScript in our Visual Studio 2015 (Update 2) setup for a non-ASP.Net project consisting of pure HTML and JavaScript. In order to disable the 'allowUnreachableCode' option, we made adjustments in the tsconfig file. It&apo ...

Dependencies for Angular 5 plugins

Will the total list of dependencies for the application be a combination of all unique dependencies from Angular plugins with their own managed dependencies in Node, even if they have some overlapping dependencies? For example, if plugin 1 has 1000 depen ...

Trouble retrieving child structural directive within parent structural directive

Seeking to connect parent structural directive with child structural directive. This shows my attempt to access the child element @Directive({ selector: '[appChildStruralDirective]' }) export class ChildStruralDirective { constructor(privat ...

When creating a new instance of a class in Angular, the methods for initialization are not included

I have a User class set up like this: export class User{ id: number = 0; fName: string = ""; lName: string = ""; constructor(){} fullName() { return this.fName + ' ' + this.lName; } email ...

Learn the steps for implementing i18n-x in Angular 2 to localize constant property values

I am currently working on localizing my Angular2 application using the i18n-x form from here. It has been successful for attributes like so: <p-dialog i18n-header header="User Details"></p-dialog> The result is: <trans-unit id="fe871da89f ...

Using Long Polling with Angular 4

I am looking for a way to monitor the progress of a certain task using API calls. To achieve this, I have developed a service that executes these API calls every 1.5 seconds Main Component private getProgress() { this.progressService.getExportPr ...

Showing Arrays in Angular on HTML Page

I have created an array that stores multiple arrays with 3 indexes each. An example of the structure looks like this: (3) [Array(3), Array(3), Array(3)] 0: (3) [199.4, 10.5, 19] 1: (3) [47.2, 2.1, 23] 2: (3) [133.6, 5.3, 25] In my HTML, I want to display ...

Announce enhancements to a Typescript library

Utilizing Sequency's extendSequence() feature to enhance all Sequence instances with a custom method: import Sequence, { extendSequence, isSequence } from 'sequency' import equal from '@wry/equality' class SequencyExtensions { e ...

What is the method for displaying an object as JSON on the console in Angular2?

I've been utilizing a service to input my form data into an array within my angular2 application. The information is organized in the following manner: arr = [] arr.push({title:name}) After executing console.log(arr), it displays as Object. However, ...

What is the process of transforming two forms into components and then integrating those components into a view in Angular 5?

Currently, I have two forms running smoothly on the same component as shown in InfoAndQualificationComponent.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from "@angular/forms"; @Component({ selector: ...

npm encountered an error while trying to fetch the requested package when running ng new app

I'm working on developing a new application using the ng new app command. Everything goes smoothly until reaching the final CREATE message below. At that point, it gets stuck for hours (literally) at the "Installing packages (npm)..." stage. Eventu ...

The formatting in vscode does not apply to .tsx files

For a while now, I've relied on the Prettier extension in Visual Studio Code for formatting my code. However, since switching to writing React with Typescript, I now need to configure Prettier to format .tsx files accordingly. ...

Is it possible to use conditional logic on child elements in formkit?

I am a bit confused about how this process functions. Currently, I am utilizing schema to create an address auto complete configuration. My goal is to have the option to display or hide the fields for manual input. This is the current appearance of the ...

NGRX Store: struggling to retrieve value from store

Currently, I am working on setting up a basic NGRX store. The goal is to have a value in my Store (specifically called chipSelected: string), display that value in AA.component.ts, and be able to change it in BB.component.ts using a button click. In esse ...