Using { emitEvent: false } alongside patchValue will not trigger valueChanges on an Angular 4 formgroup

I currently have a formbuilder group where I am monitoring changes using valueChanges. Whenever a change is detected, I trigger a save function and then refresh the form:

 this.ticketForm.valueChanges.debounceTime(1000).distinctUntilChanged()
 .subscribe(data => {
   this.saveTicket();
   this.refreshTicket();
 })

Afterwards, I reload the form and update the data in various form fields (as well as other areas on the page such as a change log) using patchValue method, like this:

    this.ticketForm.patchValue(ticket, { emitEvent: false });

However, despite setting emitEvent to false, it seems to be causing an endless loop of saving the form. Is this issue related to Angular 4 or Ionic 3, or could it be due to my misunderstanding of how the process works?

Answer №1

To enhance the functionality, include onlySelf: true in addition to emitEvent: false as shown below:

this.ticketForm.patchValue(ticket, {emitEvent: false, onlySelf: true});

Answer №2

Due to my reputation, I am unable to leave a comment, so I will share my thoughts in response to @Craig Wayne here instead.

If you use emitEvent:false, it will only work when monitoring changes in the form control with:

this.form.valueChanges.controlName.subscribe(val => doSomething(val));

However, if you are linking to model modifications on the element, the event will be triggered regardless:

<input (ngModelChange)="doSomething($event)"/>

Answer №3

Dealing with Angular 9.1.13, I encountered a persistent issue. I attempted to utilize the methods FormControl.setValue and FormGroup.patchValue, including the recommended parameters

{emitEvent: false, onlySelf: true}
in various permutations. Despite this, the valueChanges observable continued to trigger.

Ultimately, what resolved the issue for me was:

myForm.disable();
myForm.patchValue({myControl: ''}, {onlySelf: true, emitEvent: false});
myForm.enable();

Answer №4

What are the benefits of using patchValue every time a value changes as opposed to setting it once during initialization?

In my own experience, I encountered this issue in a different scenario while creating an option between two required FormControl's

I had one field clearing out another field (as intended, only one should be filled out), but then the subscribe function triggered the original field to clear as well. Setting emitEvent:false didn't solve the problem because I needed my validators to run on each update. By adding if(value) condition, it helped prevent cascading patches. See the example below:

this.formGroup.controls.item1.valueChanges.subscribe(value => {
   if(value){
     this.formGroup.patchValue({
       'item2':null
     })
   }
})

this.formGroup.controls.item2.valueChanges.subscribe(value => {
   if(value){
     this.formGroup.patchValue({
       'item1':null
     })
   }
})

Note: To keep things simple, I omitted the .pipe(takeUnitl(this.destroy$)) method. If you skip this step, there may be a memory leak.

Answer №5

I encountered a situation where none of the provided solutions worked for me, so I had to resort to manual intervention:

Initially, I created a boolean variable within the class as follows:

private flagStopChangeEvent = false;

Subsequently, I crafted the following method, leveraging rxjs pipe along with filter:

private getControlChangesWithRestrictions(control: AbstractControl): Observable<any> {
  return control.valueChanges.pipe(
    filter(_ => !this.flagStopChangeEvent)
  );
}

To monitor changes, I utilized the following snippet:

this.getControlChangesWithRestrictions(this.form).subscribe()

Whenever I needed to make modifications to the form without triggering events, I executed the following steps:

this.flagStopChangeEvent = true;
this.form.patchValue(/*patch value*/)
this.flagStopChangeEvent = false;

Answer №6

To address this issue, I decided to include the skip function in my rxjs pipe

this.form.valueChanges
    .pipe(skip(1)).subscribe();

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

Using TypeORM with a timestamp type column set to default null can lead to an endless loop of migrations being

In my NestJs project using TypeORM, I have the following column definition in an entity: @CreateDateColumn({ nullable: true, type: 'timestamp', default: () => 'NULL', }) public succeededAt?: Date; A migration is gene ...

Navigating Cross-Origin Resource Sharing (CORS) Challenges within

Currently in the process of developing an API utilizing our API server script and attempting to establish communication with the API on the IONIC framework application. Progress is being made, however, encountering a recurring issue with the cross-origin b ...

How to effectively manage blank strings, null values, and undefined values when filtering in Angular

I have created a custom pipe to filter values within an array of objects. While the basic functionality is in place, I am encountering difficulties when handling empty strings, nulls, and undefined values. When any of these values are passed to the pipe, t ...

Whenever I attempt to launch my cross-platform application on an android device, an error occurs

I am currently in the process of developing a cross-platform application using NativeScript with Angular. While it runs smoothly on web, I encounter several errors when trying to run it on Android. Despite resolving many issues, there is one error that has ...

The error message "NextFunction does not have the property 'render'" appears when using Angular Universal in conjunction with Express

When attempting to implement server-side rendering for my Angular 6 app, I encountered the following error while using the Angular CLI universal demo as a reference: Property 'render' does not exist on type 'NextFunction'. This is the ...

An issue arose when attempting to forward the request with a self-signed certificate in the chain for the Angular CLI API

When working with IBM WebSphere Application Server (WAS), we are able to add certificates to the truststore in order to resolve any certificate-related issues. How should we handle this process when using npm? ...

Expanding on the http class to utilize custom properties within Angular2 typescript

I have developed a CustomHttp class that extends Http similar to the example provided here: To integrate this CustomHttp class, I included providers in the bootstrap function as shown below: bootstrap([ HTTP_PROVIDERS, { provide:Http, use ...

What makes TypeScript code run successfully using `node` instead of `ts-node` by mistake?

I have created a basic node.js project using TypeScript. Here is the content of my package.json file, which lists all the packages I have installed (without including ts-node): { "name": "mydemo", "version": "1.0.0", "description": "", "main": "ind ...

Crafting a Retro Style

I have an interface called Product which includes properties such as name, and I want to track changes to these products using a separate interface called Change. A Change should include the original Product as well as all of its properties prefixed with t ...

Declaring types in NGRX Effect V10 has changed since classes are no longer used, causing types to not be inferred as easily

After the V10 upgrade to NGRX, there seems to be a change where passing a type of Action to the effect is no longer possible. As Actions are now declared as functions instead of classes, I'm wondering if there's still a way to handle this in V10? ...

Exploring the power of Node JS with Promise.all and forEach within a nested array

When working on a Node app with typescript, I encountered the need to iterate through an array while calling an asynchronous function inside the loop to fetch information about related items for each item in the array. The function is called for each relat ...

Webpacker/Typescript is unable to locate a file within the Rails asset pipeline

I'm currently experiencing difficulty importing a file from the rails asset pipeline as webpack seems to be unable to locate it. Here is the content of my tsconfig.json: { "compilerOptions": { "declaration": false, "emitDecoratorMetadata": ...

Bluemix is equipped with a robust build pipeline that allows users to easily set their

I'm in the process of deploying an angular 2 app on Bluemix, with the code stored on GitHub. My goal is to have the app deploy automatically whenever I push changes, so I've set up a pipeline for this purpose. Initially, I started with the build ...

Setting the TypeScript version while initializing CDK

When creating a new CDK app in typescript, I typically use the following command: npx --yes <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9babdb299e8f7e8eae1f7eb">[email protected]</a> init app --language typesc ...

Step-by-Step Guide: Building a Reusable Component for Angular Material Data Table in Angular 5

I have multiple components that display data in a tabular format. I am looking to refactor the code into a reusable data table component so that other components can utilize it instead of duplicating the table in each component. However, I am unsure how ...

Is there a way for me to distinguish between a user connecting from the intranet or the internet?

I am currently working on an Angular application with Java backend. I have been tasked with verifying whether a user logging in is doing so from the internet or the internal network where our app is deployed. This verification is necessary as I need to re ...

The file node_modules/angular2-qrscanner/angular2-qrscanner.d.ts has been detected as version 4, while version 3 was expected. Resolving symbol

We're encountering a Metadata error that is causing obstacles in our deployment process. This issue is preventing the execution of ng build. Below, you will find the configuration details along with the complete error trace. ERROR in Error: Metadata ...

What is the best method to extract the values of objects in an array that share

var data= [{tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, ...

The variance in module types within the tsconfig.json file

When configuring your project in tsconfig.json, you may come across the following options: { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": t ...

Is there a way to obtain the dimensions of an image link in Angular?

Looking to verify the dimensions of an image link, specifically if it is 1000px x 1000px and in jpg format. For example: https://www.w3schools.com/bootstrap/paris.jpg I have this link and need to extract the width and height of the image. Determining t ...