What is the best way to access values during the change event of dynamic angular forms?

Within the component.ts file, I am fetching form field values and converting them into a JSON array to create a FormGroup control. This process is functioning perfectly.

    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 utilized for iteration in the HTML section
               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 section creates 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);
          }); 
}

In the components.html file, I am utilizing the array to generate a dynamic form. This functionality is also working properly.

<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>

To change the value of a form field based on the changes in other fields, I attempted to subscribe to the valueChanges emitter of the form group variable without success.

I tried implementing this in ngOnit, but it did not produce any results in the console.

ngOnit(){

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



}

Edit 1 :

Following a suggestion from Manzur Khan, I indicated the success of the form creation event by passing the value as true, and then used this in ngOnit to capture the onchange event :

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

And within ngOnit:

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

Now I am able to log the change event in the console, but have yet to find the resolution for ${val}.

Edit 2 :

Since the val is an object, I encountered difficulties resolving ${val}, so I simply did this:

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

This provides me with all the values of the given form groups. Further optimization is still required to specifically listen to certain form controls. Nonetheless, progress has been made. Gratitude to all involved.

Answer №1

The reason this is occurring is due to monitoring value changes in the form even before it is fully loaded (as it resides within an async operation).

A potential solution could involve:

Begin by defining an Observable

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

Then, within your form code

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

Following that, in your ngOnInit function

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

Answer №2

Instead of

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

Consider enhancing the form by adding controls to it instead. I found success with this approach. You can achieve this 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));

Answer №3

In order to enhance the efficiency of this outcome further, I am in the process of fine-tuning it to specifically cater to form controls? As an alternative option for you, I have a set of solutions that might align with your needs.

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);
 }

Answer №4

To implement an event on a specific dynamic form HTML element, we can utilize the form control object. For example:

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

    });

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

Capture and handle JavaScript errors within iframes specified with the srcDoc attribute

My current project involves creating a React component that can render any HTML/JavaScript content within an iframe using the srcDoc attribute. The challenge I am facing is implementing an error handling system to display a message instead of the iframe ...

Retain the previous selection in Ng-select when clearing the current value

I am attempting to retrieve the value of an ng-select field prior to it being cleared. It appears that all change events only provide the new value at this time. <ng-select [items]="importerFields" [(ngModel)]="selectedConstant[constant. ...

Encountering an issue when transmitting a file from React/TypeScript to a C# API: "Error message stating 'The JSON value could not be converted to System.Byte[]'"

I'm working on transferring an image file from a frontend built in React/Typescript to a C# API. Here are the functions responsible for uploading a photo and sending the data to the C# API using Axios: const handleImageUpload = (event: React.ChangeEve ...

After transforming an angular project into an npm module, where should the html, css, and other files be placed? Additionally, what is the process for converting a project into

I am looking to modify the ngx-material-timepicker node module by making changes to the basic HTML and CSS of the project. However, I have found that there are no HTML or CSS files available in the node_modules-> ngx-material-timepicker folder, only TS ...

Splitting code efficiently using TypeScript and Webpack

Exploring the potential of webpack's code splitting feature to create separate bundles for my TypeScript app has been a priority. After scouring the web for solutions, I stumbled upon a possible lead here: https://github.com/TypeStrong/ts-loader/blob/ ...

Error: Unable to assign value to the property 'address' as it is undefined in SafeSubscriber._next

Struggling to pass data to an array that is declared inside the component. Only the first index of the array is being returned, while the other elements are not. I've learned that the program works asynchronously and only retrieves the first index. S ...

Changes made to the updated component fields are not reflecting on the user interface

I've encountered an issue where I can't seem to update a variable in a component that is being displayed on the UI. Even though the content of the variable changes correctly, the UI fails to reflect this change. Strangely enough, when checking th ...

Issues with compiling arise post downloading the latest Angular 2 quickstart files

My Angular 2 project was running smoothly on version 2.3, but I decided to upgrade to version 2.4. To do so, I downloaded the latest quickstart files from https://github.com/angular/quickstart After replacing my tsconfig.json, package.json, and systemjs.c ...

Logging into Azure AD from an Angular 9 Application

Struggling to authenticate with Azure AD from my Angular app. Finding it difficult to understand the process due to outdated examples on the internet. I've been following the latest documentation on GitHub but keep encountering this error when trying ...

Tips on implementing computed properties in Vue.js while using TypeScript

There is a significant amount of documentation on how to utilize Vue.js with JavaScript, but very little information on using TypeScript. The question arises: how do you create computed properties in a vue component when working with TypeScript? According ...

Firebase functions are giving me a headache with this error message: "TypeError: elements.get is not

Encountering the following error log while executing a firebase function to fetch documents and values from the recentPosts array field. Error: Unknown error status: Error: Unknown error status: TypeError: elements.get is not a function at new HttpsEr ...

Exploring the potential of Angular2's WebSocket service by efficiently accessing the parent component

I need some assistance with implementing WebSockets in my angular2 application. However, I've encountered a minor issue that I can't seem to solve. Here's what I have so far: I've created a service that has a method for creating a WebS ...

Display a jQuery dialog box with options to confirm or cancel. Submit the form when the user clicks on

One of the functionalities on my website involves a jquery-ui modal dialog that pops up when a user clicks the "Decline" button on a control within an asp.net UpdatePanel. This feature is repeated multiple times on various controls across the page. Here&a ...

Learn how to implement Angular 8 to listen for changes in an observable within an interceptor

Currently, I am in the process of developing an HTTP interceptor that aims to include an 'access level' parameter in the request. The challenge arises when attempting to extract this value from an observable named currentAccessLevel$. Unfortunate ...

Is it possible for pdfjs-dist to be used with Typescript?

Is there a way to preview a PDF as a canvas without importing pdfjs-dist into my project? I have already used the command $yarn add pdfjs-dist to install pdfjs-dist. Do I need to include any additional imports? import pdfjsLib from "pdfjs-dist/build ...

Using js/jsx files in a TypeScript + Webpack project: A beginner's guide

I encountered an issue while trying to import and utilize a regular .jsx file within my typescript project that is built with webpack. The error message I received reads: ERROR in ./src/components/App/Test.jsx 72:4 Module parse failed: Unexpected token (72 ...

Troubleshoot: ng-bootstrap Carousel Functionality Issue

While testing the various components on ng-bootstrap, I encountered an issue with getting the carousel to work. Strangely enough, all the other ng-bootstrap components are functioning perfectly. Upon implementing the code from , the result is a blank white ...

What is the process of deploying Angular Server Side Rendering (SSR) build files to Azure Web App service using FileZilla FTP?

I'm currently working on Angular SSR and utilizing the Angular official sample project for testing purposes. Steps for building the Angular SSR project: Execute npm run build:ssr This will automatically generate the dist folder, which contains both ...

The element possesses an implicit 'any' type as the expression containing 'string' cannot index the type '{}'

Question: I encountered the error "No index signature with a parameter of type 'string' was found on type '{}'. Below is the code snippet where the error occurred: const dnsListObj = {}; for (const key of dnsList) { dnsLis ...

Choose the desired option from Angular 7 / Ionic 4 dropdown menu

I am facing an issue with a piece of code that creates dynamic drop-down select options. I need to retrieve the selected values from these items. The loop in the code generates 3 to 5, or sometimes even more, different dropdowns based on API data. My goa ...