Updating a value in one input field triggers changes in several other input fields in Angular 6

I'm currently in the process of learning the basics of Angular 6 and TypeScript, and I'm struggling to figure out how to achieve a specific functionality. Essentially, I have a field where users can input a numerical value, and based on that input, I want to dynamically adjust the values in other input fields. I believe I need to implement debounceTime and use 'rxjs', as demonstrated in this tutorial: https://angular.io/tutorial/toh-pt6, but I'm having trouble getting it to work.

For example, if a user enters '100' in the "how much" field, I want the values in Tomek's and Magda's fields to automatically update to '50' (100 / 2).

https://i.sstatic.net/OhQkp.png

expense-shared.component.html

<div class="form-group">
  <label for="name">How much?</label>
  <input type="text" class="form-control" id="amount" required 
  [(ngModel)]="expense.amount" (keyup)="changeListValues(expense.amount)"
  name="amount" #amount="ngModel" placeholder="Amount in EUR">
  <div [hidden]="amount.valid || amount.pristine" class="alert alert-danger">
    Amount is required
  </div>
</div>

expense-shared.component.ts

@Input() amountList: Equally[];

changeListValues(expenseTotalAmount: number) {
        const checkedAmount = this.amountList.filter(x => x.checked).length;

        this.amountList.filter(x => x.checked).forEach(element => {
          element.quantity = this.expense.amount / checkedAmount;
        });
      }

Answer №1

Exploring Observables for Managing Input Changes

If you're looking to tackle input changes using Observables, here's how you can do it effectively.

Let's consider the following HTML form:

<form [formGroup]="heroForm">
  <label>
    Name 1:
    <input type="text" formControlName="name1" required>
  </label> 
</form>

If you want to track input changes for name1 using Observables, follow these steps in your component.ts file.

ngOnInit() {    
    this.logNameChange();
}

logNameChange() {
   const nameControl = this.heroForm.get('name1');
   nameControl.valueChanges.forEach(
      (value: string) => console.log(value)
   );
}

The above code will log the typed values in the console for you.

Check out a live example on StackBlitz: https://stackblitz.com/edit/angular7-input-change-observable?file=src/app/app.component.ts

For more details, refer to the Angular Documentation: https://angular.io/guide/observables-in-angular#reactive-forms

I hope this guide proves helpful to someone out there.

Cheers!

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

What is the best way to extract the ID from an event in TypeScript?

HTML Code: <ion-checkbox color="dark" checked="false" id="1on" (ionChange)="onTap($event)" ></ion-checkbox> TypeScript Code: onTap(e) { console.log(e); console.log(e.checked); } I am trying to retrieve the id of the checkbox. H ...

What is the best way to monitor parameter changes in a nested route?

I need assistance with managing routes const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListC ...

The error message "window is not defined in Angular Universal" indicates that the window object

While attempting to utilize @nguniversal/express-engine, I encountered an issue in the main.js file after installing and running it. The error message reads: C:\Folder\ssr\dist\ssr\server\main.js:179450 })(window, functio ...

Converting an existing array into a TypeScript string literal type: A step-by-step guide

Converting TypeScript Arrays to String Literal Types delves into the creation of a string literal type from an array. The question raised is whether it's feasible to derive a string literal from an existing array. Using the same example: const furnit ...

RTK update mutation: updating data efficiently without the need to refresh the page

I am facing an issue with my mui rating component in a post-rating scenario. Although the rating updates successfully in the data, the page does not refresh after a click event, and hence, the rating remains enabled. To address this, I have implemented a d ...

Is it possible for a voiceover artist to initiate API requests?

As I work on the registration feature of my application, I am faced with the requirement that email addresses must be unique in the database. Since I am responsible for the front-end development, I am considering creating a Value Object (VO) that can make ...

Using Angular (along with Typescript) to showcase JSON data

I previously shared this query, but unfortunately, I didn't receive many helpful responses I have a JSON file that holds the following dataset: [{ "ID": 1030980, "Component": "Glikoza (Gluk)", "Result": "16", "Date": "20.10.2018" } ...

Guide to starting a Tizen Web App project using Angular

Starting out: I have experience with Angular and am now looking to delve into Tizen for the first time. I want to create a Tizen Web Application using Angular (7.x.x) for Samsung TV. After installing Tizen Studio and its extensions, I've set up a st ...

Creating dynamic and engaging videos using Angular with the ability to make multiple requests

I am facing an issue while working with videos in Angular. I am fetching the video URLs from an API to embed them in my application using the sanitazer.bypassSecurityTrustResourceUrl function provided by Angular. The videos are being displayed correctly wi ...

Different and Basic Designs for mat-table

Is there a way to customize the appearance of the material data table (mat-table) beyond the pre-built themes? I'm specifically interested in styles like table-striped, table-sm, or table-bordered from bootstrap 4. Is it possible to apply these style ...

Incorporating a filtering search bar in Ionic React to efficiently sort pre-existing lists based on their titles

Struggling to implement a search bar in my Ionic application has been quite challenging. I've searched for examples and tutorials, but most of them are based on Angular with Ionic. The React example in the Ionic docs didn't provide much help eith ...

Obtaining access to objects in Angular 4: A comprehensive guide

I am currently working with an array in my DataComponent and I would like to pass 'string4' to my ConsumeComponent through a Service: export class DataComponent { mystring: string = ''; constructor(private myService: myService) {} ...

Using template expressions to access properties that contain spaces

Here is the code structure that I am working with: "name": { "age": [ { "data": { "how old": "23" } }, One of my JSON keys has a space in it. How can I access this pr ...

Adjusting the array when items in the multi-select dropdown are changed (selected or unselected)

I am looking to create a multi-select dropdown in Angular where the selected values are displayed as chip tags. Users should be able to unselect a value by clicking on the 'X' sign next to the chip tag, removing it from the selection. <searcha ...

Applying ORM Drizzle in cases of conflict

Here's where I'm currently at: If I use onConflictDoNothing, the plan is to insert a new record into the database. However, if a record with the same userId and provider already exists, and the apiKey of the existing record is not equal to the ap ...

I am struggling to comprehend the concept of dependency injection. Is there anyone available to provide a clear explanation for me?

I am working on a NestJS application and trying to integrate a task scheduler. One of the tasks involves updating data in the database using a UserService as shown below: import { Injectable, Inject, UnprocessableEntityException, HttpStatus, } fro ...

Transform Promise<any> into a designated type failure

Beginner inquiry concerning typescript/angular4+/ionic4. I have a service set up to make backend REST calls, and based on the response received, I need to store that data in local storage for future reference. However, I am encountering a type conversion e ...

Ways to dynamically manipulate HTML elements in Angular 5

Recently, I've been attempting to programmatically transform an HTML element. Strangely, when I update the transform value in the console tab, it changes successfully, but for some reason it doesn't reflect in the element tab of the browser. onD ...

Exploring the possibilities of customizing themes in Angular Material with Stylus for Angular 5

My project is currently utilizing the "stylus" CSS pre-processor instead of SCSS. I am interested in incorporating Angular Material themes and switching between them. While I can find documentation for SCSS, I am struggling to find resources for stylus. ...

What is the best way to access values from dynamically added components in Svelte when using data from a REST API in a loop?

Previously, I posted this query but now I've made changes to utilize a REST service for retrieving the item list. Everything functions as expected when the data is hardcoded, however, I encounter undefined values when using data from the REST service. ...