"Exploring the world of subscribing in Angular's reactive

I'm struggling with Angular's reactive form valueChanges event. I want to react to user inputs in order to prevent or correct them, but every approach I've tried so far has resulted in a Maximum call stack size exceeded error when subscribing to the event.

const controlArray = <FormArray> this.formArray.get('items');
    this.formArray.get('items').valueChanges.subscribe(val => {
      val.forEach(s => {
        controlArray.controls.forEach(control => {
          const con = control.get('symbol');
          if (con.value === s.symbol) {
            con.setValue(s.symbol.toUpperCase());
          }
        });
      });
    }); 

My ultimate goal is to change each letter input to uppercase. Is there a simpler way to achieve this without iterating through each keyboard event?

I also attempted using (change)="function(value)", but it only gets called when I press enter on the keyboard :/

Answer №1

If you're looking for a simpler method, consider utilizing the input directive. Let's say you have an object named book, and you wish to convert its title field to uppercase as the user inputs text.

HTML-Form

<input id="book-title" name="book-title" (input)="book.title = book.title.toUpperCase();"/>

Answer №2

You've encountered a problem known as exceeding the maximum call stack size. This happens when you get stuck in an endless loop, where each change triggers another event, leading to a never-ending cycle.

To resolve this issue, avoid triggering the event repeatedly within your observer by using the native patchValue method like this:

    this.myCustomForm.patchValue({
      fieldSymbol: this.myCustomForm.value.fieldSymbol.toUpperCase()
    }, { emitEvent: false })

You can also incorporate this approach into a generic buildForm function for better efficiency:

buildForm() {

//...FormControls
this.myForm= new FormGroup({
  fieldSymbol: new FormControl('', Validators.required)
});

//..ValidationMessages
this.validationMessages = {
'fieldSymbol': [
    { type: 'required', message: 'Please fill this field' }
  ]
}

//..observe value change
this.myForm.valueChanges.subscribe((data) => {
  //..other stuff
  //..some controls

  //..what you probably need
  this.myCustomForm.patchValue({
   fieldSymbol: this.myCustomForm.value.fieldSymbol.toUpperCase()
  }, { emitEvent: false })
});

}

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

Ways to grant access beyond the local host

I am having trouble accessing my Angular2 application outside of localhost. I can easily navigate to localhost:3030/panel, but when I try to use my IP address like 10.123.14.12:3030/panel/, it does not work. Can someone please help me fix this issue? I am ...

The integration of Meteor Angular2 with Mongodb underwent significant external modifications

I have been experimenting with a basic Meteor Angular 2 application that simply reads from a database. I also have another app that interacts with the same database. However, whenever there is a change in the database, I encounter an error in my Meteor app ...

Create an asynchronous method within an object-oriented programming (OOP) class

Presenting my Activity class. export class Activity { _name: string _goIn: boolean constructor(name: string) { this._name = name; this._goIn = false; } isGoIn() { return this._goIn; } setGoIn() { // instructions to asyn ...

Transform this React-Redux function component into a class component

After following the guide provided on https://github.com/Microsoft/TypeScript-React-Starter to set up my project, I encountered an example with a react component as a function. This is the current code snippet: export interface Props { name: string; ...

What methods can be used to check for incorrect type of a function argument in ts-jest?

I have been experimenting with a TypeScript function lately. To speed up my testing process, I decided to utilize ts-jest. However, I stumbled upon an issue that seems tricky to resolve. Despite exploring various ts-jest options, I couldn't find a so ...

Upon loading a website, the Chrome browser will automatically set the zoom level to 80%

Recently, I've encountered a perplexing issue with Chrome where my website is automatically zoomed out from 100% to 80%. It seems that browsers cache zoom settings based on the domain and apply them when users revisit the site. However, in this case, ...

Generating a JSON array from dynamically added list items using Angular 2: A step-by-step guide

I'm currently learning Angular 2 and I have a question about auto-complete functionality. I have an input field that suggests categories when searching, and when I click on one of the suggestions, it adds a new category to a list called category-tags ...

Retrieving all records in Firestore that have access to their child documents

I'm attempting to retrieve all the documents from each child collection (ratings) and update the average rating in the foobar document. However, I am encountering an error in one of my callable functions: Unhandled error RangeError: Maximum call stack ...

Why hasn't the variable been defined?

Why am I receiving an error message saying "test is not defined" in this code? Even though I have properly defined the variable in another service file, it seems to be causing issues here. Any insights on what could be going wrong? import { Injectable } f ...

Storing Data Locally in Angular with User Authentication

Using angular8, I encountered an issue where logging in with USER1 credentials, closing the browser, and then attempting to log in with USER2 credentials still logged me in as USER1. While adding code to the app component resolved this problem, I faced an ...

Exploring table iteration in Angular 7

I am looking to create a table with one property per cell, but I want each row to contain 4 cells before moving on to the next row... This is what I want: <table> <tr> <td> <mat-checkbox>1</mat-checkbox& ...

What steps can be taken to store the data from a prior HTTP request in an observable before initiating a new request?

Here is the code for the parent component: this.statisticsService.getData().subscribe(data => this.processData(data)); processData(data: DataWrapper) { if (!isNullOrUndefined(data) && data.table.rows.length > 1) { this.noDataAvai ...

Exploring Angular 5's *ngFor directive with an array of objects

Here is the data I am working with: Initial set of data: var input = [ {ru: "R201", area: "211", unit: "211"}, {ru: "R201", area: "212", unit: "NONE"}, {ru: "R201", area: "HCC", unit: "NONE"}]; Desired result data: var result = [ {area: ...

Retrieving array values to be used as Typescript data types

Is there a method to transform array values into strings? Here is what I came up with: class A { public keys = ['name', 'age'] } type ArrayKeys = P in A['keys'] // 'name' or 'age' Any suggestions on ...

Having trouble with an Angular subscribe error that says "Property 'subscribe' does not exist on type 'AngularFireList<unknown>'.ts(2339)"? Let's find a solution together!

My goal is to retrieve data from a Firebase RDB in the data service by using the following function: this.getOrgId() .subscribe((orgId: string) => localStorage.setItem('orgId', orgId)); getOrgId() { return this.db.list(/users/${this.uId ...

What is the best way to export Class methods as independent functions in TypeScript that can be dynamically assigned?

As I work on rewriting an old NPM module into TypeScript, I encountered an intriguing challenge. The existing module is structured like this - 1.1 my-module.js export function init(options) { //initialize module } export function doStuff(params) { ...

What is the reason behind the occurrence of `(User & { _id: Schema.Types.ObjectId; }) | null` when calling findById?

Today marks my debut using typescript and mongoose. Here's a glimpse of what I've worked on. Type export interface User extends Document { _id: ObjectId; lastName: string; } Schema const userSchema = new Schema<User>({ lastName: { t ...

Creating an HTTP gateway with Observables

When dealing with multiple requests, I need to pause them until the authentication of the http request has been confirmed. Essentially, I require an http gate where some requests can pass without authentication, while others need to wait for the token to b ...

What are the reasons for discouraging the use of canActivate always returning false?

I've searched extensively to avoid duplicate postings and tried various solutions, but unfortunately, none of them have resolved the issue. My implementation of canActivate to secure a dashboard seems to be working properly, but it's always retu ...

Efficiently Handling Multiple File Uploads using Angular and Multer

I'm seeking guidance on integrating multer (nodeJS) with Angular 7. Despite trying several solutions, I am unable to successfully upload any files. In my case, the files originate from a ReactiveForm: <mat-tab label="Documents" for ...