Reactive form loses preloaded data due to ExpressionChangedAfterItHasBeenCheckedError when modal is dismissed

Within my project, I have a sidenav that contains various links. One of these links directs to a component that presents some input data.

Below is the TypeScript code:

@Input() data: MyData;
myModal: BsModalRef;
editForm: FormGroup;

ngOnInit(){
    this.editForm = this.formBuilder.group({
        inOne: [this.data.one, [Validators.required]],
        inTwo: [this.data.two, [Validators.required]]
    });
}

showModal() {
    const config: ModalOptions = {
        initialState: {
            message: 'Some dynamic tip message'
        }
    };
    this.myModal = this.modalService.show(MyModalComponent, config);
}

The HTML code associated with it is as follows:

<form [formGroup]="editForm" (ngSubmit)="editForm.valid && save()">
    <h3>SIMPLE MODE</h3>
    <app-text-input 
        [formControl]="editForm.controls['inOne']" [type]="'number'">
    </app-text-input>
    <app-text-input 
        [formControl]="editForm.controls['inTwo']" [type]="'number'">
    </app-text-input>
    
    <button class="btn btn-info btn-sm" (click)="showModal()">Tip</button>
</form>

For the "app-text-input" component, the corresponding code snippet is provided below:

<div class="form-group">
    <input 
        [class.is-invalid]='ngControl.touched && ngControl.invalid' 
        type={{type}} 
        class="form-control"
        [formControl]="ngControl.control" 
        placeholder={{label}}"
    >
    <!-- some validators -->
</div>

Although this code functions properly initially with preloaded data displaying correctly, issues arise after interacting with the modal pop-up. Upon closing the modal, the previously loaded data remains in the inputs. However, upon returning from another page within the sidenav, the pre-loaded data disappears. An error related to expression changing is displayed in the console:

core.mjs:6485 ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'ng-valid': 'true'. Current value: 'false'.. Find more at https://angular.io/errors/NG0100
    at throwErrorIfNoChangesMode (core.mjs:6733:1)
    at bindingUpdated (core.mjs:12710:1)
    at checkStylingProperty (core.mjs:16451:1)
    at ɵɵclassProp (core.mjs:16359:1)
    at NgControlStatus_HostBindings (forms.mjs:1367:1)
    at processHostBindingOpCodes (core.mjs:9251:1)
    at refreshView (core.mjs:9530:1)
    at refreshComponent (core.mjs:10655:1)
    at refreshChildComponents (core.mjs:9280:1)
    at refreshView (core.mjs:9534:1)

An attempted solution involved implementing the following:

ngAfterViewChecked(): void {
    this.changeDetectorRef.detectChanges();
}

While this resolved the error issue, the problem of missing preloaded data persisted. What could be causing this?

Answer №1

After a long process of troubleshooting, I finally discovered the root cause of this issue - it was due to my save() function interacting with values from all inputs.

The solution involved tweaking the logic within the (ngSubmit) event:

<form [formGroup]="editForm" (ngSubmit)="editForm.valid ? save() : null">

With this modification, everything now functions as intended.

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

"Utilize XML parsing to convert data into JSON format and set up subscription functionality

My current task involves converting an XML string to JSON using xml2js. I then need to send and subscribe to the result in another component. getLastWeekSnow = function(){ let headers = new Headers(); headers.append('Access-Control-Allow-Origin' ...

Encountered a hiccup during the deployment of an Angular application on Heroku

I've been working on deploying an Angular app called "test-app" to Heroku via GitHub and everything seems to be going smoothly, except for setting up the express routing function. I've tried different paths, but Heroku keeps throwing this error: ...

Angular2 encountering a lack of service provider issue

After finding the code snippet from a question on Stack Overflow titled Angular2 access global service without including it in every constructor, I have made some modifications to it: @Injectable() export class ApiService { constructor(public http: Http ...

Unable to finish the execution of the ionic capacitor add android command

My current project needs to add android as a supported platform, so I tried running the command: ionic capacitor add android. However, when I run the command, it stops at a prompt asking me "which npm client would you like to use? (use arrow keys)", with ...

Can you give me some insights about what an Action Creator is?

function createRefDoneAction(widgetsArray: widget[]): WidgetAction { return { type: actionTypes.REFRESH_WIDGET_DONE, widgets: widgetsArray }; } Could you please clarify the necessity of having two sets of parameters (e.g. 'wid ...

Wijmo encountered an error: Expected date but received different data

I have been encountering an issue with the Wijmo date picker. When I input a proper date format for the Wijmo date, sometimes it is accepted without any errors while other times an error message pops up. My code for setting the form value is: this.mfForm. ...

Implementing Angular's Advanced Filtering Across Multiple Data Fields

I am looking to create a custom filter for a list. Here is an example of the Array of Objects: myList: [ { "id": 1, "title":"title", "city":"city name", "types":[ { ...

How does a brand new installation of VSCode believe it comes pre-equipped with TypeScript capabilities?

Operating on Windows 10 Enterprise, After investing several hours and experimenting on various VMs, Interesting Observation #1 Upon opening a .ts file in vscode, it appears to be recognized as TypeScript 2.3.4 as per the screenshot provided below: http ...

Guide on customizing a dropdown button in a class-based Angular library with version 4 or higher

My dilemma revolves around utilizing the Angular Material library for a drop-down navigation bar. The issue at hand is my desire to hover through the list, yet I am unable to tweak the style within HTML. Fortunately, I can easily make alterations in Chrome ...

Navigating the use of property annotations in Mapped Types with remapped keys

After exploring the concept of Key Remapping in TypeScript, as shown in this guide, I am wondering if there is a way to automatically inherit property annotations from the original Type? type Prefix<Type, str extends string> = { [Property in keyo ...

I am interested in creating a versatile validation system that can be applied to any Angular form. The standard reactive approach is already completed and functioning effectively

I am looking for a way to implement generic validation in Angular forms that can be used across different components. The basic reactive form is already set up and running smoothly, but I need assistance with implementing a more versatile approach. Can a ...

Sending data with Angular using a POST requestorMaking a

I'm attempting to make an HTTP POST call in Angular with a body, but I'm not receiving the response I expect. callAddGroupAPI(formId, groupJSON){ let json = { "group":groupJSON } this.http.post(this.apiURL+'AddGroup/' ...

There are zero assumptions to be made in Spec - Jasmine analyzing the callback function

I've encountered a challenge with a method that is triggered by a d3 timer. Each time the method runs, it emits an object containing several values. One of these values is meant to increase gradually over time. My goal is to create a test to verify wh ...

Angular 6 introduces a new component with cascading comboboxes for easier data organization

In my Angular 6 project, I have successfully implemented a shared component called country-state. It is functioning perfectly. VIEW MY PERFECT WORKING EXAMPLE However, upon dividing the country-state component into separate country and state components, ...

The back button in the Chrome browser fails to trigger a page refresh within an Angular application

The code snippet above was used in an attempt to refresh the page when the back button is pressed, but it only works inconsistently in Chrome. The issue seems to be that despite correctly detecting the back button press, the page does not always refresh ...

Can I specify which modal or component will appear when I click on a component?

Working on a small Angular 5 project, I have a simple component that represents a food product shown below: [![enter image description here][1]][1] This component is nested within my main component. When this component is clicked, a quantity component/m ...

Conversion of UTC timestamp to a timestamp in the specified timezone

this.selectedTimezone="Pacific/Kiritimati"; //this value will come from a dropdown menu These records represent the data.body returned by an API call. Iterating through each record in the dataset: { We are creating a new Date object based on the ...

Leveraging vuex in conjunction with typescript allows for efficient management of state in namespace modules,

I am currently integrating vuex with typescript and namespaces module in my project. Within this setup, I have two distinct modules: "UserProfile" and "Trips". So far, everything is functioning smoothly within the confines of each module. However, I have ...

What are the steps to execute jest in an AWS Lambda environment?

I'm looking to execute my end-to-end test post-deployment for the ability to revert in case of any issues. I've followed the guidelines outlined in this particular blog post. Below is my lambda function: export async function testLambda(event: A ...

"Exploring data trends with an ng2-charts line graph displaying x and y axis values

I am attempting to showcase a function using ng2-charts, with a specific set of x and y values. However, the display is currently not showing my values correctly. https://i.sstatic.net/1iULy.png Here is an example dataset: chartDataSet: ChartDataSets[] = ...