how to get values on change event in dynamic angular forms?

angular reactive forms valuechanges
adding form fields dynamically in angular 6
angular dynamic forms
angular reactive forms set value
how to get form control value in angular 7
angular 7 reactive forms
angular 4 dynamic form fields
angular2 form control value changes

On component.ts file I am fetching the form field values in json array like this and converting it to an FormGroup control like this. This is working perfectly fine.

    getJsonForm(){
      let base_url = 'example.org'
      let getform_query = '/Base/formfieldsgenerator_get';
      let getform_endpoint = base_url.concat(getform_query);

     this.AllFormData = [];

        this.http.get('getform_endpoint'.'?tabpgrpid='+this.tabpgrpid+'&tabgrpname='+this.tabgrpname+'&usertabgrpname='+this.usertabgrpname+'&moduleid='+this.moduleid+'&templateid='+this.templateid+'&all_mod_data='+this.all_mod_data,{headers: this.headers}).subscribe(
        res => { 
         this.AllFormData = res;

                // this array is used to iterate in html side
               this.newfdata[element] = [];
               this.newfdata[element]['properties'] = [];


   Object.keys(res['com'][element]['schema']['properties']).forEach(inputKey => {
                      this.newfdata[element]['properties'].push(res['com'][element]['schema']['properties'][inputKey]);

                });

            // this is used to create form controls and form groups

                this.objectProps = Object.keys(res['com'][element]['schema']['properties']).map(prop => { 

          return Object.assign({}, { key: prop} , res['com'][element]['schema']['properties'][prop]);
          });

   for(let prop of Object.keys(res['com'][element]['schema']['properties'])) {

          formGroup[prop] = new FormControl(res['com'][element]['schema']['properties'][prop].value || '', this.mapValidators(res['com'][element]['schema']['properties'][prop].validation));

                }
        });

      this.form = new FormGroup(formGroup);
          }); 
}

Now on components.html side I am using the array like this to generate the dynamic form. This is also working fine.

<form (ngSubmit)="custom_submit(form.value)" [formGroup]="form" >
         <div *ngFor="let input1 of newfdata[tabname].properties">   
                <ng-container *ngIf="input1.type=='string'">
                                <div>
                                     <mat-form-field>
                                     <input matInput  [formControlName]="input1.field_name" [id]="input1.field_name" type="text"  placeholder="{{input1.title}}">
                                     </mat-form-field>   
                                </div>
                            </ng-container>
         </div>  
</form>

Now I want to change the value of one form field based on changes on previous form fields. For that I am not able to subscribe to the valuechanges emitter of the form group variable.

I have tried this on ngOnit but it's not working and not producing any result in console.

ngOnit(){

   this.form.valueChanges.subscribe(val => {
                    this.formattedMessage = 'My changed values for is ${val}.';
                    console.log(this.formattedMessage);
                  });



}

Edit 1 :

After suggestion from Manzur Khan, I have passed the valueas true for the success of formcreated event and then in ngOnit used the value like this to get the onchange event :

      this.form = new FormGroup(formGroup);
      this.dataService.change_current_form_created("true");

and in NgonIt

this.dataService.last_form_craeted_message.subscribe(data => {
  if(data=="true") {
    this.form.valueChanges.subscribe(val => {
         this.formattedMessage = 'My changed values for is ${val}.';
            console.log(this.formattedMessage);
        });
}
});

Now I am able to log on change event in console but not able to get the resolution for ${val}.

Edit 2 :

Since the val is object, I was not able to resolve ${val} somehow,I Simply did

   this.form.valueChanges.subscribe(val => {
            console.log('the changed value is',val);
        });

It gives me all the values of given formgroups. I still need to optimize this result further so that I just listened to specific form controls. But it has give me a road to go. Thanks all.

It's happening because you are listening to value changes of the form even before the form is present(since it's inside async)

You can try something like this

First declare an Observable

formCreated: Subject<boolean> = new Subject();

Then in your form code

this.form = new FormGroup(formGroup);
this.formCreated.next(true)

and then in your ngOnInit

this.formCreated.subscribe(data => {
  if(data) {
    this.form.valueChanges.subscribe(val => {
         this.formattedMessage = 'My changed values for is ${val}.';
            console.log(this.formattedMessage);
        });
}
})

Reactive Forms in Angular: Listening for Changes, Listen for change events in your reactive forms by subscribing to the Reactive form instances like FormGroup and FormControl have a to valueChanges to update instance variables or perform operations. In this post you'll learn how to use Leaflet with Angular to generate shapes on a dynamic and … Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a basic form control, progress to using multiple controls in a group, validate form values, and create dynamic forms where you can add or remove controls at run time.

Instead of

formGroup[prop] = new FormControl(res['com'][element]['schema']['properties'][prop].value || '', this.mapValidators(res['com'][element]['schema']['properties'][prop].validation));

Try to add controls to the form, it worked for me. You can do that by using form.addControl:

formGroup.addControl(prop, new FormControl(res['com'][element]['schema']['properties'][prop].value || '', this.mapValidators(res['com'][element]['schema']['properties'][prop].validation));

Building dynamic forms, To make it faster and easier to generate different versions of such a form, you can to generate new forms automatically, according to changes in the data model. In this tutorial you will build a dynamic form that presents a basic questionaire. of an individual question based on values in the data-bound question object. Learn how to create a dynamic form in Angular and then create tests for the form to ensure it works as expected. This article will cover testing of dynamic forms in Angular. Dynamic forms in Angular are forms that are created using reactive form classes like Form Group and Form Controls. We will write tests for these forms to ensure that they

I still need to optimize this result further so that so that I just listened to specific form controls?? , I have some different solution for you which may work for your requirements.

template.html

<form (ngSubmit)="custom_submit(form.value)" [formGroup]="form" >
 <div *ngFor="let input1 of newfdata[tabname].properties">   
  <ng-container *ngIf="input1.type=='string'">
   <div>
    <mat-form-field>
     <input matInput (ngModelChange)="modelChanged($event,input1.field_name)"[formControlName]="input1.field_name" [id]="input1.field_name" type="text"  placeholder="{{input1.title}}">
    </mat-form-field>   
   </div>
  </ng-container>
 </div>  
</form>

component.ts

 public modelChanged(ev, formName) {
   console.log('Jarvis Event', ev);
   console.log('control value', this.form.get(formName).value);
 }

FormControlName, Reactive Forms � Validate form input � Building Dynamic Forms Syncs a FormControl in an existing FormGroup to a form control element by name. validator: ValidatorFn | null, Read-Only Async validator function composed of all the async validators registered with this directive. changes, SimpleChanges. A object of� User actions such as clicking a link, pushing a button, and entering text raise DOM events. This page explains how to bind those events to component event handlers using the Angular event binding syntax. Run the live example / download example. Binding to user input eventslink. You can use Angular event bindings to respond to any DOM event

We can use form control object to create an event on a particular dynamic form HTML element. e.g.

this.form.controls["DynamicFormControlId"].valueChanges.subscribe(val => {

    });

Reactive forms, Reactive forms have methods to change a control's value programmatically, which A form array defines a dynamic form, where you can add and remove controls at The FormGroup directive listens for the submit event emitted by the form� Angular 10 Popup Notification with SweetAlert2 Example Angular and Laravel 7 Password Reset for JWT Tutorial Laravel 7 Angular Token-Based Authentication with JWT Deploy Angular 10/9 App to Production with Firebase Hosting Angular 10/9/8 Firebase CRUD Operations with Reactive Forms Connect Firebase Realtime NoSQL Cloud Database with Angular App

Angular 2 Dynamic Forms field valueChanges event not working , I have used checkedItemsChanged event as a workaround to track these value changes, but it adds a lot of boilerplate to the code and doesn't� Example built with Angular 8.0.2. Other versions available: Angular: Angular 9; This is a quick example of how to build a dynamic form with validation in Angular 8 using Reactive Forms. The example is a simple order form for selecting the number of tickets to purchase and entering a name and email address for each ticket.

Creating Dynamic Forms with Dependent Controls and Angular , How to dynamically render form controls that depend on each other's values the problem arises when form controls have to depend on each other's values. onChange : a function that triggers the sendMessage when the� The ValueChanges is an event raised by the Angular forms whenever the value of the FormControl, FormGroup or FormArray changes. It returns an observable so that you can subscribe to it. It returns an observable so that you can subscribe to it.

Angular 10, reactive forms with dynamic rows, validation and value , This is a complex angular 10 reactive forms guide with the example on How to listen to form value changes; How to create dynamic rows with form array input that is subscribed we have to stop triggering this listener so we� you'll learn angular input checkbox change event. you will do the following things for checkbox change event angular. You can call checkbox change event in angular 6, angular 7, angular 8 and angular 9 application. So, let's follow bellow step to create simple example. you can also see bellow screen shot for checkbox in angular app.

Comments
  • Please add the relevant code to your query. Its to confusing whats your actual query is due to extra stuff.
  • Not put the code in ngOnInit, just AFTER your line: this.form = new FormGroup(formGroup). Well, for clarity, create a function and call it after the line
  • "Now I want to change the value of one form field based on changes on previous form fields". Well, think if the value must belong to the form or not.e.g. if your "field" formattedMessage is "My ChangeValue"+input1.value, you can not have this "field", just a < span>{{"My change Value "+form.getControl('input1').value}}< /span>
  • @mayur : This is the actule code snippt to make you understand the whole scenario. Nothing here is extra.
  • When I do this . it gives me two errors, ERROR TypeError: Cannot read property 'subscribe' of undefined at AddComponent.ngOnInit and Cannot read property 'next' of undefined at SafeSubscriber , So should I need to defined this.formCreated somewhere? IF so, how?
  • @Manzur Khan, You needn't create a formCreated submited. just, after create the form (is a sync function), create the subscription to valueChanges
  • @Eliseo , I am checking with your approach.
  • @Manzur Khan, I created one common shared service which holds the value as true after form is created like this. this.form = new FormGroup(formGroup); this.dataService.change_current_form_created("true"); where this.dataService is commong service I am using to pass the messages to diff. components. Now I am able to log the value change event in the console but Getting only message like this, My changed values for is ${val}.'; and not the value itself.
  • @Manzur Khan, Please orovide correct defination or declaration of Formcreated, (In my case I created an behaviour, observable subject). So that I can mark your answer as correct.