Pay attention to variations in the form control within a nested form group

export class ApplyComponent implements OnInit {
    formApply: FormGroup;
    postCodeInput: boolean = true;

    constructor(private fb: FormBuilder) {}
    ngOnInit() {
        this.formApply = this.fb.group({
            firstName: ["", Validators.required],
            currentUKAddress: this.fb.group({
                flat: ["", Validators.required],
                years: ["", Validators.required]
            })
        });
        this.onChanges();
    }

    onChanges(): void {
        ...
    }

I am trying to track changes in the years field. Despite my attempts within the onChanges() method, I can't figure out why nothing seems to be working... I have tried:

- this.formApply.get('currentUKAddress.years').valueChanges.subscribe(data => {
            console.log('Form changes', data);
        })

 - this.formApply.controls.currentUKAddress.get('years').valueChanges.subscribe(data => {
            console.log('Form changes', data);
        })



- this.formApply.controls.currentUKAddress.controls['years'].valueChanges.subscribe(data => {
            console.log('Form changes', data);
        })

and various other approaches. However, each time I encounter a Typescript compiler error stating either: property does not exist on type AbstractControl or Object is possibly null.

Answer №1

Sometimes the type checker struggles to reach a decision. That's when the Non-null assertion operator (!) steps in to save the day:

this.addressForm.get('currentUSAddress.years')!.valueChanges.subscribe(info => {
            console.log('Data changes', info);
        })

It works perfectly...

Answer №2

 let currentDate =  <FormControl>(this.formApply.get('currentUKAddress.years'));
currentDate.valueChanges.subscribe(info => {
            console.log('Updates in form', info);
        })

Answer №3

One possible approach is as follows:

this.formApply.get('currentUKAddress').get('years').valueChanges.subscribe(data => {
            console.log('Form changes', data);
        })

Answer №4

ngOnChanges is specifically designed for tracking changes in input/output variables.

To monitor changes in text inputs, you should follow this approach:

<input type="text" formControlName="flat" (input)="flatChangeListener($event)">

In your TypeScript file:

flatChangeListener(event) {
  // event will contain the input value.
}

Repeat this process for other input fields, and you'll be all set! If it's not a text input, please let me know so that we can adjust the event listener accordingly (for example, using (change) instead of (input) for a select).

Answer №5

  Whenever there is a change in the value of ['lugar']['pais'] in this.frmParamsTit, the following code will execute: 
    data.pais=='GT'? this.showDepartments=true:this.showDepartments=false;
  });

Answer №6

My approach to handling the form structure was similar to the following:

this.formApply.controls.currentUKAddress.valueChanges.subscribe(
 currentUKAddress =>
    {
      console.log("years", currentUKAddress.years) // Monitoring the incoming years value

    }
 )

Unfortunately, none of the solutions above were effective for me. Instead, I focused on listening to currentUKAddress directly rather than just the years property.

I hope this concept proves useful to someone else.

Angular version: 7

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 showcase two different arrays' data in a single Angular view?

I have 2 different arrays retrieved from an API with no common FK or any other identifier. Even though my TypeScript code produces the expected results, the view remains blank. The debugging results are provided as comments in the code snippet below: ngO ...

You have to include the necessary request body in the front-end request to address the

After successfully testing a POST request to add a new entity to the database from my project back-end using Postman, I encountered an error when trying to do the same from the front UI (I'm using Angular 4): Required request body is missing. Failed ...

Error: Unable to access fileName property as it is null

I encountered an ERROR while running the 'ng serve' command for my Angular project. Below is the error message: C:\Users\lgqli\angular\oshop-new>ng serve \ Generating browser application bundles (phase: setup)... - @a ...

Issue with Angular Datatable not displaying content when [dtTrigger] directive is included in the HTML table - Angular 14

Upon adding [dtTrigger] = "dtTrigger" to the HTML table, I encountered an issue where the datatable ceased rendering. All the features of the datatable were no longer visible on the page. Removing [dtTrigger] = "dtTrigger" from the HTML ...

Issues with updating table data when clicking the "Remove Selected" button a second time in Angular 8

Whenever I click the "Remove Selected" button on my table, the selected rows with checkboxes should be deleted. The issue is that it works perfectly fine the first time I click the button, but if I repeat the same steps (click the checkboxes and then click ...

Encountering problem when attempting to incorporate fade in/fade out effect animation

I have a webpage that features multiple buttons, each triggering a fade-in/fade-out animation when clicked. This animation also involves changing the contents of a specific div. Though everything is functioning properly, there is a brief moment (about hal ...

What could be causing the issue with converting a Firestore timestamp to a Date object in my Angular app?

Currently, I am developing an Angular project that involves using a FireStore database. However, I have encountered a problem with the setup. Within my Firestore database, I have documents structured like the example shown in this image: https://i.sstatic ...

Solving TypeScript circular dependencies using () => TypeName

Recently encountered circular reference issues with Typescript. Suggestions provided on https://github.com/microsoft/TypeScript/issues/27519 recommend using () => TypeName. However, I am unsure how to effectively utilize the variable in this context. ex ...

Integrating Auth0-js with the usePostMessage functionality

Encountering difficulties when compiling an Angular application that incorporates the auth0-js package. The code utilizes the method renewAuth(options: RenewAuthOptions, callback: Auth0Callback<any>): void;, yet it seems to be causing issues as the p ...

What steps should I take to choose esNext from the typescript menu within visual studio 2017?

When utilizing dynamic import with TypeScript in Visual Studio 2017, I encountered the following error: TS1323(TS) Dynamic imports are only supported when the '--module' flag is set to 'commonjs' or 'esNext'. I attempted to c ...

The CORS policy has restricted access to the XMLHttpRequest from the specified origin at "http://...." to 'http://localhost:4200'

I'm currently facing a challenge while trying to make an API call, as I encountered a CORS error. When attempting with "https://....", the service failed and threw the following error: Status Code: 422. OPTIONS 422 (Unprocessable Entity) Access to ...

Displaying the input text directly is ineffective when the dropdownlist value changes due to the presence of another dropdownlist

How can I tackle the issue of dynamically populating dropdown lists with cascading categories and subcategories? I currently have two dropdown lists where the subcategory dropdown is filled based on the selected category. I also need to display an input fi ...

Develop a personalized Observable object

Is it possible and acceptable to create a custom observable? For instance, if I have data stored in my cache, I would like to create a custom observable before making an HTTP request: Here is what the request looks like: private device: Device; getDevice ...

Alter the color of the mat-select once it has been chosen

Is there a way to keep the same color for mat-select focus even after selection? I have checked the documentation but couldn't find any information on this. <mat-form-field> <mat-label>Choose an option</mat-label> <mat-select ...

update the element that acts as the divider in a web address (Angular)

Is it possible to modify the separator character used when obtaining the URL parameters with route.queryParams.subscribe? Currently, Object.keys(params) separates the parameters using "&" as the separator. Is there a way to change this to use a differe ...

Conceal a text field depending on the value within a hidden field that was populated automatically by a JavaScript function

I encountered a peculiar issue recently. I have a form with a field for entering card numbers. There is a JavaScript code that automatically detects the type of card (such as Maestro, Visa, etc.) based on the entered number. If the detected card type is &a ...

Developing UIs in React that change dynamically according to the radio button chosen

Problem Statement I am currently developing a web application feature that computes the heat insulation factor for a specific area. You can view the live demonstration on Codesandbox <a href="https://codesandbox.io/p/github/cloudmako09/btu-calc/main?im ...

Crafting redirect rules in React that avoid redirecting to the same route

In my project, there is a file named AuthenticatedRoute.tsx, which serves as a template for all the protected/authenticated routes in my Router.tsx file. export default ({ component: C, authUser: A, path: P, exact: E }: { component, authUser, path, ex ...

Shuffle and Place indented list

I have a bunch of ideas and a list of projects. I need to choose one idea and match it with a project. I followed this guide to implement the drag and drop feature, but encountered an issue where every project gets assigned the same idea when dragging and ...

Route parameters that repeat multiple times (n occurrences)

When creating a route with route parameters, how can you define it to allow the same parameter to be repeated n times? For example: { path: '/route/:id1/:id2/:id3/:id4', // etc. component: SomeComponent } Is there a simpler way to ...