The function ValueChange remains uninvoked

Query: The issue is that valueChanges is only triggered for the entire form and not for specific controllers. Although this approach works, it returns the complete object.

    public ngOnInit(): void {
          this.form.createWagonBodyForm();

            this.goodCode$ = this.form.wagonBodyForm.valueChanges.subscribe((val) => {
            console.log(val);
        })
}

The problem arises when attempting to detect changes in the goodCode value through valueChanges.

public ngOnInit(): void {
  this.form.createWagonBodyForm();

const goodCode = this.form.wagonBodyForm.get('goodCode');
this.goodCode$ = goodCode.valueChanges.subscribe((val) => {
        console.log(val);
    })

}

This portion of my code contains several formControlNames, but I have provided only two for which I need change detection:

<div class="row m-0 table-responsive panel wagon-form-body" [formGroup]="form.wagonBodyForm">
<table class="table gr table-bordered">
    <thead class="panel-head">
        <tr>
            <th width="5%" style="min-width: 100px">{{ 'navigation.WagonN' | translate }}</th>
            <th width="5%"> {{ 'navigation.Cargocode' | translate }} </th>
        </tr>
    </thead>
    <tbody class="panel-body">
        <tr *ngFor="let waggon of form.wagonBodyForm.controls; index as i" [formGroup]="waggon">
            <td>
                <input type="text" class="form-control gr-input validate" minlength="8" maxlength="8" required
                    OnlyNumbers formControlName="vagonNumber" />
            </td>
            <td>
                <input type="text" class="form-control gr-input validate" required minlength="7" maxlength="8"
                    OnlyNumbers formControlName="goodCode" />
            </td>
        </tr>
    </tbody>
</table>
export class FormService {
    public wagonBodyForm!: FormArray;

    public createForm(item?: ISmgsWaggon) {
        if (item) {
            this.wagonBodyForm.push(
                this.fb.group({
                    vagonNumber: new FormControl(item.vagonNumber),
                    goodCode: new FormControl(item.goodsGng),
                })
            );
        }
        else {
            this.wagonBodyForm.push(
                this.fb.group({
                    vagonNumber: new FormControl(''),
                    goodCode: new FormControl(''),
                })
            );
        }
    }
}

Answer №1

When implementing a Dynamic form, it is important to specify the index of goodCode that you wish to focus on.

createForm(item?: any): void {
    const formGroup = this.fb.group({
      vagonNumber: new FormControl((item) ? item.vagonNumber : ''),
      goodCode: new FormControl((item) ? item.goodsGng : ''),
    });

    const index = this.wagonBodyForm.length;
    this.wagonSubSubscription = formGroup.valueChanges.subscribe(value => {
      console.log('I receive value change at No ' + (index + 1) + ' with value: ' + JSON.stringify(value));
    });

    this.wagonBodyForm.push(formGroup);
}

Additional optimization:

You can optimize your code like this:

public createForm(item?: ISmgsWaggon) {
    this.wagonBodyForm.push(
        this.fb.group({
            vagonNumber: new FormControl((item) ? item.vagonNumber : ''),
            goodCode: new FormControl((item) ? item.goodsGng : ''),
        })
    );
}

View full example on Stackblitz: stackblitz

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

"Utilizing the same generic in two interface properties in Typescript necessitates the use of the

I have created an interface as follows: interface I<T>{ foo: T arr: T[] } After defining the interface, I have implemented an identity function using it: const fn = <T>({foo, arr}: I<T>) => ({foo, arr}) When calling this function l ...

Angular 7 throwing errors of undefined variables

I encountered an error message that says Property 'country' does not exist on type 'ViewComponent'. Did you mean 'country$'? I'm at a loss on how to resolve this issue. I understand that there is an undefined variable ca ...

Achieving a successful Reset Password functionality with ASP.NET Core and Angular

I've been working on setting up password recovery for users who forget their passwords and need to reset them. One issue I'm facing is figuring out how to properly generate the recovery link that is sent to the user via email. Should the link le ...

Angular 8 throws a TS2339 error, yet the code is functioning perfectly and delivering the desired output

Upon compiling my code, I encountered the following error: ERROR in src/app/home/home.component.ts:13:37 - error TS2339: Property 'name' does not exist on type 'string | Type'. Property 'name' does not exist on type &ap ...

Error encountered when running Angular 11 with SSR using @nguniversal/express-engine: "ReferenceError: globalThis is not defined"

Encountering issues while attempting to integrate @angular/fire with Angular 11 and @nguniversal/express-engine for server-side rendering (SSR). Upon initializing AngularFireModule in app.module.ts, errors arise when running the commands npm run dev:ssr or ...

Converting UK DateTime to GMT time using Angular

I am currently working on an angular project that involves displaying the start and end times of office hours in a table. For instance, the office operates from 8:30 AM to 5:30 PM. This particular office has branches located in the UK and India. Since u ...

Guide on maintaining Spring Security authentication across Angular front-end

Following the initial feedback on my query, I made adjustments to my Spring Security setup and successfully logged in and accessed a test endpoint using Postman. However, when the same endpoint is called by Angular post successful login, the request fails, ...

Implementing a component prior to a directive in Angular 2

In my Angular2 application, I created a small component that serves as a directive to display a small view in various parts of the application. I only specify the options within the component where I am using this directive. This directive always require ...

Having trouble retrieving data from Spotify API within Angular application

Upon attempting to retrieve a json response from the Spotify API, I encountered the following error: XMLHttpRequest cannot load https://api.spotify.com/v1/search?query=eminem&offset=0&limit=20&type=artist&market=US. Request header field Ac ...

Steps to fix the postinstall error in Angular CLI

Can anyone lend a hand in resolving the following error? npm ERR! errno -4058 npm ERR! @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c4f40456c14021c021a">[email protected]</a> postinstall: `node ./bin/p ...

Correctly inputting MongoDB-specific collection methods which are currently defaulting to "any"

I'm facing an issue with typing Mongo collection method responses in my app. Specifically, I am having trouble finding a way to type the response of the deleteMany method. The documented response should look like this: { "acknowledged" : true, "delete ...

What is the best way to incorporate a Vue single file component into a Typescript-infused view?

Despite trying numerous methods, I consistently encounter build or runtime errors. To my surprise, I have not come across a functional example or post related to this inquiry after extensive research. I initiated a new project with Typescript using the Vue ...

The input type "number" does not seem to be compatible with the currency pipe feature

The currency pipe seems to not be working when using the input type number. The web page is not displaying any value. I have searched various blogs and it appears that the currency pipe only works with input type text, but my requirement necessitates the ...

Typescript i18next does not meet the requirement of 'string | TemplateStringsArray NextJS'

While attempting to type an array of objects for translation with i18next, I encountered the following error message in the variable navItems when declaring i18next to iterate through the array Type 'NavItemProps[]' does not satisfy the constrain ...

Developing Your Own Local Variable in Angular with Custom Structural Directive ngForIn

I am hoping for a clear understanding of this situation. To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below: import {Directive, Input, OnChanges, SimpleChan ...

Create a pipeable stream that does not trigger any events when data is piped

I have been trying to utilize the renderToPipeableStream function from React18, and although it is functional, I am struggling with handling the pipe properly. The key section of my code involves an array of strings representing HTML. I am splitting the s ...

Creating a JSON file using an object to send requests in Angular

In my Angular 7 project, I am trying to send a multipart request to the server that includes a file (document_example.pdf) and a json file containing a data object (data_object_example.json). The content of data_object_example.json is as follows: { " ...

Encountering an issue while attempting to start ng serve due to the error message stating "Module '@angular/compiler-cli' cannot be located"

I am facing an issue with running my Angular project. Whenever I try to execute ng serve, it fails with the following error: dev@716a5115c45c:~/project$ npx ng serve Cannot find module '@angular/compiler-cli' Error: Cannot find module '@ang ...

(Chrome Extension, Angular 7) How come a mat dialog displays properly on a webpage but fails to render in a chrome extension? (Including a repo for reproduction)

I am facing an issue with my Angular 7 code that uses material dialogs. While everything works fine when viewed as a webpage, the problem arises when I try to load it as a chrome extension. The dialogs render incorrectly and make the entire extension windo ...

What is the process for extracting components from a JSON file using an observable in Angular?

Take a look at this snippet of code: response: any; fetchData(url: any) { this.response = this.http.get(url); } ngOnInit(): void { fetchData("url.com/data.json"); console.log(this.response) } When I check the console, I see Obser ...