Unable to access the value property of null in Angular reactive form when attempting to retrieve the value

{
  "estimate_number": "2020-1234",
  "brand": "PF",
  "floor": "Laminaat",
  "floor_type": "Normaal",
  "plint_type": "Hoog",
  "floor_installer": {
    "id": "14",
    "name": "Maestro"
  },
  "address": {
    "street": "Straatnaam 19",
    "city": "Amsterdam",
    "postal_code": "1111AB",
    "province": "Noord-Holland"
  },
  "notes": "Test note"
}

How come when I access

const city = this.addEventForm.get('address.city').value;
, it returns a value (in this case Amsterdam), but accessing
const floorInstaller = this.addEventForm.get('floor_installer.id').value;
results in an error message in the developer console saying
ERROR TypeError: Cannot read property 'value' of null at CalendarComponent.push..

This JSON object represents a reactive form in Angular.

The FormBuilder code used to create the form:

        // FormBuilder
        const datesGroup = this.fb.group({
            start_date: '',
            start_time: { hour: 7, minute: 30 },
            end_date: '',
            end_time: { hour: 17, minute: 30 },
        });

        const addressGroup = this.fb.group({
            street: '',
            city: '',
            postal_code: '',
            province: '',
        });

        this.addEventForm = this.fb.group({
            event_dates: datesGroup,
            estimate_number: '',
            brand: '',
            floor: '',
            floor_type: '',
            plint_type: '',
            floor_installer: { id: '', name: '', },
            address: addressGroup,
            notes: '',
        });

Answer №1

Hey there! I believe you can retrieve the value using the code snippet below:

this.addEventForm.get("address").get("city").value

Here is the code snippet that I tested:

const addressGroup = this.fb.group({
  city: ""
});

this.addEventForm = this.fb.group({
  address: this.fb.group({
    city: ""
  })
});
getValue() {
 console.log(this.addEventForm.get("address").get("city").value);
}

For the HTML, you can use the following:

<form [formGroup]="addEventForm">
 <div formGroupName="address">
    <input formControlName="city" >
 </div>
</form>
<button (click)="getValue()">Get Value</button>

I hope this explanation is helpful to you. For now, I have only focused on retrieving the city value. Feel free to include all the controls as needed.

Answer №2

Perhaps the direct object { id: '', name: '', } is not being recognized properly by the get() function. Consider assigning floor_installer its own form builder group.

const floorInstallerGroup = this.fb.group({
  id: '',
  name: ''
});

this.addEventForm = this.fb.group({
.
.
.
  floor_installer: floorInstallerGroup,
.
.
}

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

Combining Google app endpoints with a phonegap app: Step-by-step guide

I've been working on a Phonegap client application and have developed all the necessary web services using Google Endpoints. However, I am facing an issue with using the API. In my index.html file, there is this script: <head><script> ...

Utilizing and interpreting the input data provided by the user in jQuery

While following the tutorial at , I am trying to extract specific parameters from the user input to generate a corresponding URL. Below is the code snippet I am working with: <html> <head> <title>USGS Earthquake Feed</title> ...

I am trying to collapse the table header but I am having trouble doing so

@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100); @import url(https://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100); body { bac ...

What's the reason for seeing "1:powershell" in the terminal when using react.js?

Can anyone explain why the terminal shows "1:powershell" in react.js? https://i.sstatic.net/1LyHe.png https://i.sstatic.net/5K95B.png ...

Unit tests using ngMock never seem to reach completion when dealing with external promises

I'm currently facing a challenge in unit testing the handling of external promises being resolved or rejected. The issue arises when using the ngMock module, as it seems to prevent these promises from ever completing. This is particularly problematic ...

Use jQuery to duplicate an image that has the "active" class, then assign it as the background image for a div element

I am utilizing the default carousel from Twitter Bootstrap to create a basic slider. What I aim to do is, when an item becomes active, the image inside that item should be duplicated and set as the background image for the div with the 'testimonials-b ...

Enhancing URLs with jQuery/AJAX: A Comprehensive Guide to Adding Parameters

Whenever I try to use the get method on an HTML form, the submitted data automatically appears in the URL. You can see what I mean here. Interestingly, when attempting to achieve the same result with JQuery and AJAX using the get method, the data doesn&apo ...

Tips for obtaining the top 3 highest-value objects in a JavaScript array over all other elements

I am working with an array that contains objects, each with two properties: name and value. array = [ { name: 'name1', value: 0 }, { name: 'name2', value: 2 }, { name: 'name3', value: 4 }, { name: 'n ...

Adding javascript code to each page in an asp.net application

I am in the process of implementing GTM on a website with over 400 pages where the GTM script needs to be placed. Is there a way to automatically inject the GTM script on every page right after the body tag? The website utilizes a mix of technologies, in ...

Explaining how to define a function parameter that accepts a class as an argument in TypeScript

I'm looking to develop a function that can take the class type (the class itself, not an instance) as a parameter and then instantiate an object based on that input. Let me illustrate this with an example: //All classes that could be passed as param ...

Achieve horizontal bar movement by utilizing google.visualization.DataTable in a left-to-right motion

I am exploring the possibility of reversing the direction of a chart(bar) using google.visualization.DataTable. In the current setup, the bar progresses from left to right, but I wish for it to move from right to left instead. Below is what I have attempte ...

Find with user-friendly input/label removal function (Ionic 2)

I have embarked on creating a recipe application where users can search for recipes by ingredients. I want to enhance the functionality of the search feature so that when users press the spacebar to enter the next input, it appears as a label below with an ...

Error message: "The post request is returning a value of 0

I am trying to pass a variable from JavaScript to PHP using the POST function. Here is what I have tried: The line causing issues: $.post(window.location, {idafevent: event.id}); JavaScript code snippet: eventRender: function(event, element) { elemen ...

*ngIf is dynamically inserting elements rather than removing and replacing them

My Code <i *ngIf="!isFollowing" class="far fa-bell"></i> <i *ngIf="isFollowing" class="fas fa-bell"></i> Type of isFollowing is Boolean Whenever the value changes to true or false, a new element is displayed based on the express ...

Tips for effectively simulating the formik useFormikContext function while writing unit tests using jest

I've created a simple component (shown below) that aims to fetch data from the Formik FormContext using the useFormikContext hook. However, I'm facing some challenges when writing unit tests for this component. It requires me to mock the hook, w ...

What is the best way to take control of DOM alterations?

In the project I'm currently working on, the client has a modal box with its display property set to none. Upon clicking the CTA button, it triggers the application of the fadein and fadeout classes. This results in a change from display:none to displ ...

An easy way to activate the save button automatically

Is there a way to automatically enable the save button when a user checks the checkbox and enters text in the input field? I'm not sure what steps are needed or if there is an alternative approach to achieve this. jQuery("input[type='text&apos ...

What prevents using super() to set values on an immutable record?

I'm in the process of setting up a brand new Redux store state, starting from scratch. Instead of reinventing the wheel, I decided to replicate an existing Redux store structure that I had previously created and simplified. Initially, I attempted to ...

Tips for concealing or deleting a title attribute from an SVG component in Angular 2

I have successfully integrated SVG icons into my Angular 2 application. However, when hovering over the icons, they display the 'Icons' title. I utilized Angular SVG Icon for inline SVG to apply CSS styles. My goal is to eliminate this title fro ...

The performance of my JavaScript function seems to be lagging

I'm currently gathering extensive data from an API using an async function that iterates through a large amount of information using a loop. I'm sending about 100 requests and it's taking approximately 8 seconds to complete. Are there any t ...