Ensuring that the field remains active in Angular2 even after editing it with a value

When the 3rd dropdown value is selected in the first field dropdown, it enables the 2nd field. However, when I edit and change a different value, since the 2nd field is disabled, I receive null or undefined as the value. I want the 2nd field to retain its value if the 1st field is not changed in edit mode.

HTML:

TS:

private FormInit() {
    //Add
    if (!this.Details) {
      this.detailsForm = this.FB.group({
        Type: ['', Validators.required],
        ID: [{ value: 0, disabled: true }],
      });

    } else {
      // edit
      this.detailsForm = this.FB.group({
        Type: [this.Details.data.Type, Validators.required],
        SourceID: [{ value: this.Details.data.ID, disabled: true }],

      });
      if (this.Details.mode == 'readOnly') {
        this.detailsForm.disable();
      }
    }
  }

ADD and Edit functions:

public save() {
    let addParams = this.detailsForm.value;
   addParams.Type = addParams.Type ? addParams.Type: 0;
    this.Service.add(addParams).subscribe(res => {
      console.log(res);
      this.successMessagePopUp(res);
    })
  }

  public update() {
    let updateParams = this.detailsForm.value;

    this.Service.update(updateParams).subscribe(res => {
      this.successMessagePopUp(res)
    })
  }

I am looking for a solution where, when the 3rd dropdown value is selected, the 2nd field remains enabled in edit mode and only gets disabled if another value is selected?

Answer №1

Typically, when disabled values are used in angular, they appear as undefined.

Note: Based on your requirements, here is a suggestion:

private FormInit() {
    if (!this.Details) {
      this.detailsForm = this.FB.group({
        Type: ['', Validators.required],
        ID: [{ value: 0, disabled: true }],
      });

    } else {
      // edit
      this.detailsForm = this.FB.group({
        Type: [this.Details.data.Type, Validators.required],
        ID: [{ value: this.Details.data.ID }],

      });

     if (this.Details.data.Type == 3)
     {
         this.detailsForm.get("ID").enable();
     }
     else
     {
         this.detailsForm.get("ID").disable();
     }

      if (this.Details.mode == 'readOnly') {
        this.detailsForm.disable();
      }
    }
  }

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

Best practice for including Angular in the list of dependencies for an npm library

I have developed a small angular package on NPM that I consistently maintain to be compatible with all the latest versions of angular. In my package.json file, I have included angular in the list of peerDependencies to ensure they are always available in p ...

Tips for synchronizing response JSON with TypeScript interface in Angular 6

I am retrieving a list of files that have been uploaded from a backend endpoint, and it comes back in this format: [ { "filename": "setup.cfg", "id": 1, "path": C:\\back-end\\uploads\\setup.cfg", ...

How can I make the snackbar open multiple times in a row?

Check out this codesandbox I created to show an issue. When you click the button, a MUI snackbar opens. However, if you close it and try to reopen it, nothing happens. Do you think the problem is related to how I'm using hooks? Explore the sandbox h ...

Is there a way to search through an array of object arrays in JavaScript for a specific key/value pair using lodash or any other function?

I am faced with a task involving an array of objects. Each object has a key that needs to be used to search through sets of arrays containing similar objects. The goal is to determine if all the arrays contain the same value for a specific key in my object ...

Troubleshooting React/Jest issues with updating values in Select elements on onChange event

I am currently testing the Select element's value after it has been changed with the following code: it("changes value after selecting another field", () => { doSetupWork(); let field = screen.getByLabelText("MySelectField") ...

Unable to execute @angular/cli following installation

I recently set up the @angular/cli on my MacBook. The Node server version I am using is v6.9.5 and npm version 3.10.10. To install the @angular/cli, I executed the command below: sudo npm install -g @angular-cli However, whenever I try to run any ng co ...

Nativescript encountered an error due to an undefined variable called FIRAuth

I'm currently working on a project using Nativescript. While everything runs smoothly with Firebase on the local emulator, I encounter errors when testing the application on my iPhone. The specific error message is: CONSOLE LOG file:///app/vendor.js ...

I will not be accessing the function inside the .on("click") event handler

Can someone help me troubleshoot why my code is not entering the on click function as expected? What am I missing here? let allDivsOnTheRightPane = rightPane.contents().find(".x-panel-body-noheader > div"); //adjust height of expanded divs after addi ...

What is the reason that {a: never} is not the same as never?

Is there a reason the code {a: never} cannot be simplified to just never? I believe this change would resolve the issues mentioned below. type A = {tag: 'A', value: number} type B = {tag: 'B', value: boolean} type N = {tag: never, valu ...

Troubleshooting: Ngx-Echarts Animation Issue at Startup

I've been working on integrating ngx echarts into my Angular app, but I'm facing an issue with the animation during the initial load of the chart. Take a look at this Stackblitz example where you can see that the bars render quickly on initial lo ...

Error: Unable to Locate Module (Typescript with baseUrl Configuration)

Struggling to implement custom paths in my TypeScript project, I keep encountering the "webpackMissingModule" error due to webpack not recognizing my modules. I've attempted various solutions without any success. Any suggestions or ideas? Some packa ...

What is the best method for confirming that a string is not undefined, null, or an empty string in an Angular template?

Is there an efficient method to verify whether a string is not undefined, null, or '' in an angular template? If the value is valid, then show this section. <div class="flex-row date-area" *ngIf="startDate !== undefined && startDate ...

Get an angular xml file by utilizing the response from a C# web API download

I am trying to download an XML file from a database using a Web API in C#, which returns the file as byte[]. How can I properly read these bytes and convert them into an XML file on the client side using Angular? Despite attempts with blobs and other metho ...

Tips for extracting a value from a geojson response using a specific key

When analyzing the geojson response below, I am trying to access the following: Type and Segments To achieve this, I attempted the following: return data["type"] //does not work, error received return data["features"][0]["properties"]["segments"] ...

Angular - Detecting Scroll Events on Page Scrolling Only

I am currently working on implementing a "show more" feature and need to monitor the scroll event for this purpose. The code I am using is: window.addEventListener('scroll', this.scroll, true); Here is the scroll function: scroll = (event: any) ...

Implementing the strictNullCheck flag with msbuild

Can strict null checks be enabled when compiling using msbuild? I see in the documentation that the compiler option is --strictNullChecks, but I couldn't find any specific entry for it on the msbuild config page. Is there a method to activate this f ...

Problem with Ionic2 star rating component

I am currently learning how to use rating stars in my Ionic2 app. I came across a helpful link on setting up rating stars in Ionic2. However, I encountered an issue when I tried to add the output tag. Can someone assist me with this problem? rating.html ...

I am verifying the user's login status and directing them to the login page if they are not already logged in

My goal is to utilize ionViewWillEnter in order to verify if the user is logged in. If the check returns false, I want to direct them to the login page and then proceed with the initializeapp function. My experience with Angular and Ionic is still limite ...

Whenever I try to retrieve a value using the key from ModelBindingContext.ValueProvider.GetValue(key

When working with AngularJS to manipulate a complex parent object with different behaviors for its children server-side, I encountered an issue while implementing the CreateModel function as suggested in this answer. The problem arises when any call to bin ...

Adjusting the height of an Angular CDK virtual scroll viewport based on dynamic needs

Currently, I am developing an Angular table with the cdk Virtual Scroll feature. Is there a method to adjust the scroll viewport's height dynamically? While the standard style property works, I am encountering difficulties setting the value using ngSt ...