What is the best way to change multiple parameters using ngModelChange?

I have a requirement in my application to update 3 values using a single ngModelChange event.

The component structure is as follows:

model: any = {};
images: any;
public input = true;
public dropdown = false;
images : any;

constructor(...services) {

}

ngOnInit() {
let projectId = +this.route.snapshot.paramMap.get('projectId')
this.model.projectId = projectId
this.model.ram = 1073741824
this.model.cpu = 1
this.model.diskSize = 1073741824
this.images = this.getImages()
this.onChange(this.images)
}

onChange(test: any) {
this.model.ram = test.ram
this.model.cpu = test.cpu
this.model.diskSize = test.diskSize
}

getImages(){
this.imgService.getImages().subscribe(x => this.images = x)
}


hideInput(){
this.dropdown = true;
this.input = false;
this.onChange(this.images)
}

hideDropdown(){
this.input = true;
this.dropdown = false;
}

The HTML markup is as shown below:

<div class="row">
      <div class="col-3 mt-3">
        <div class="form-check form-check-inline">
          <input class="form-check-input" (click)="hideDropdown()" type="radio" 
         name="inlineRadioOptions" id="inlineRadio1" value="option1" checked>
          <label class="form-check-label" for="inlineRadio1">Image Url</label>
        </div>
        <div class="form-check form-check-inline">
          <input class="form-check-input" (click)="hideInput()" type="radio" 
        name="inlineRadioOptions" id="inlineRadio2" value="option2">
          <label class="form-check-label" for="inlineRadio2">Pre Registered Images</label>
        </div>       
      </div>
      <div class="col-9" *ngIf="input">
        <mat-form-field class="example-full-width">
          <input matInput name="imageUrl" required [(ngModel)]="model.imageUrl" trim 
          pattern="(^(\/{1})([a-zA-Z]+))*^(ht)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0- 
          9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$"
          >
        </mat-form-field>
      </div>
      <div class="col-9" *ngIf="dropdown">
        <mat-form-field class="example-full-width">
          <mat-label>Please choose image</mat-label>
          <select matNativeControl name="imageUrl" required [(ngModel)]="model.imageUrl" 
          (ngModelChange)="onChange($event)">           
            <option *ngFor="let item of images" [ngValue]="item.imageUrl">
              {{ item.name }}
            </option>
          </select>
        </mat-form-field>
      </div>
    </div>

To update the CPU value along with RAM and Disk Size:

<div class="row">
      <div class="col-3 mt-3 labelText">
        <span class="spanText">CPU</span>
      </div>
      <div class="col-7">
        <mat-slider min="1" max="32" step="1" name="cpu" class="example-full-width" 
        [(ngModel)]="model.cpu">
        </mat-slider>
      </div>
      <div class="col-2">
        <div class="circle mt-1">{{model.cpu}}</div>
      </div>
    </div>

The JSON result returned from the backend API:

[
   {
      "id":1,
      "name":"cedric-ubuntu",
      "imageUrl":"someurl",
      "diskSize":10737418240,
      "ram":1073741824,
      "cpu":1
   },
   {
      "id":2,
      "name":"arzu-ubuntu",
      "imageUrl":"someurl",
      "diskSize":10737418240,
      "ram":2147483648,
      "cpu":2
   }
]

I attempted using (change) event but it did not work. One similar logic updates another dropdown list based on ID and functions correctly. However, for multiple parameters, I am facing issues.

Answer №1

If you need to work with multiple parameters, FormArray is the way to go. Here is an example of how the code would look:

const arr = new FormArray([
  new FormControl(),
  new FormControl()
 ]);

For more information, check out these resources: Angular FormArray and DynamicForm Example

Answer №2

Your implementation of the "onChange" function for both ngModelChange and the function "hideInput" is causing issues. In hideInput, you are passing the object "images" to the function, but in the select tag, you are only passing the $event without an "image" object, which is why it's not functioning correctly.

UPDATE

The issue lies in the following code block:

images: any; <--- declared twice 

onChange(test: any) { <--- You're receiving one object here
    this.model.ram = test.ram
    this.model.cpu = test.cpu
    this.model.diskSize = test.diskSize
} 

hideInput(){
    this.dropdown = true;
    this.input = false;
    this.onChange(this.images) <--- In this line, you're passing the object/array images
} 

(ngModelChange)="onChange($event)"> <----- Here you're passing the select $event instead of the selected object

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

Switching "this" keyword from jQuery to TypeScript

A piece of code is functioning properly for me. Now, I aim to incorporate this code into a TypeScript application. While I prefer to continue using jQuery, I am unsure how to adjust the use of this to meet TypeScript requirements. if ($(this).width() < ...

Securely connecting Angular front end with NodeJS backend server using HTTPS encryption

I am currently using a frontend built with Angular 7 and ngx-admin, along with a backend developed in nodeJS and Express. The issue: The Angular frontend uses HTTPS to communicate with the backend via HTTP. This has caused the following problem: Mixed Co ...

What is the best approach for designing a UI in Angular to showcase a matrix of m by n dimensions, and how should the JSON format

click here for a sneak peek of the image Imagine a matrix with dimensions m by n, containing names on both the left and top sides. Remember, each column and row must be labeled accordingly. ...

"Is it possible to add an entire object to formData in one

I am looking to send both an image list and product data to an ASP.net api using formData. I have successfully sent the images, but now I am struggling with appending the entire object. I have come across some methods in JS like JSON.stringfy(object) or Ob ...

Facebook sharing woes: Angular app's OG meta tags fail to work properly

Trying to figure out how to properly use og tags for the first time. I'm working on an Angular application and need to share my app link on Facebook with all the necessary tag information included. In my index.html file, I've inserted the follow ...

The method beforeEach in angular2/testing seems to be failing as it is not

Currently, I am utilizing Gulp, Gulp-Jasmine, and SystemJS to conduct tests on an Angular2 demo application. The setup is fairly straightforward. I have successfully implemented a System.config block and loaded the spec file. However, I encounter an error ...

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...

Angular (version 2.4.5) is throwing an error stating that you cannot bind to the 'ngTemplateOutletContext' property because it is not recognized as a valid property of the 'ng-container' component

While I understand that there have been similar questions regarding errors during the migration from Angular 4 to 5, my issue pertains to building an Angular 2.4.5 project with webpack. Despite successful compilation without errors, attempting to run the p ...

A guide on fixing the issue of the missing X-Frame-Options header in Angular

I'm currently working on an Angular-14 project. One challenge I'm facing is: The X-Frame options are missing - The X-Frame-Options header is either not set or set improperly to DENY or SAMEORIGIN. This can leave the application vulnerable to c ...

After logging in, the query parameters (specifically code and state) are still present

After logging into my SPA, the query parameters code and state are not removed from the URL. This causes an issue when refreshing the page because the login flow attempts to use the parameters in the URL again. For example, here is the URL after logging in ...

Navigate smoothly in Angular 4 with Spring Boot without the need for hash codes in the URL routing

Here is the scenario I am facing: I am currently using Spring Boot with Angular 4 I generate a build file using angular-cli and place it under the resource -- static folder. When I run my pom.xml, all the files in the static folder are copied to target ...

Verify that the Angular service has been properly initialized

I am currently testing my Angular service using Karma-Jasmine and I need to verify that the loadApp function is called after the service has been initialized. What would be the most effective approach for testing this? import { Injectable, NgZone } from ...

What is the best way to create a function that can securely search for a URL containing parameters while ensuring type safety?

I am working on a NextJS/React application. We have a large object containing internal URLs, each with a createPath function that looks similar to this: const URLS = { dashboard: { createPath: ({ accountNumber }: { accountNumber: string }) => ...

Creating an Angular Accordion/Zippy Component: A Step-by-Step Guide

I am currently tackling a project involving the presentation of a list of grievances in a zippy/accordion format. The data set I work with is an array of key-value pairs found in my component.ts file, shown below: isExpanded: boolean; complaints: any[] = ...

Is it possible to utilize the same selector in two components, but with different template syntax?

Currently, I am working with two components: DetailPage and ListPage. The template for both components is as follows: <my-detailpage> <my-header>{{ text }} </my-header> <my-content>{{ content }} </my-content> </my-detaip ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

Prior to the ngAfterContentInit hook being triggered, simulate class members

I am facing an issue with a component that queries its content child. Here's the code snippet: @ContentChild(InputControlDirective, { read: ElementRef }) public inputControl: ElementRef; To handle this, I have implemented the ngAfterContentInit hook ...

Tips for denoting unnecessary non-null assertions in Typescript

Incorporated this wrapper (source) into the project I'm currently working on: export function expectToBeDefined<T>( arg: T, ): asserts arg is Exclude<T, undefined> { expect(arg).toBeDefined(); } The objective is to eliminate the usage ...

Heroku: Unable to retrieve resource - server returned a 404 (Not Found) status code

I successfully developed my Angular 6 app on my local machine with everything working perfectly. However, after deploying the project to Heroku and running my app here Testing App, I encountered an error in the console browser. Failed to load resource: ...

Angular 11 Import Guide for MAT_DATE_LOCALE

I am struggling with importing 'mat-date-locale' in Angular 11 modules. The link I followed didn't provide a solution, as mentioned here: Cannot find name "MAT_DATE_LOCALE" with Material.angular Datepicker. In my project, I have A ...