When trying to update a form field, the result may be an

Below is the code for my component:

this.participantForm = this.fb.group({
      occupation: [null],
      consent : new FormGroup({
        consentBy: new FormControl(''),
        consentDate: new FormControl(new Date())
      })
 })

This is the HTML section:

<form [formGroup]="participantForm">
    <div formGroupName="consent">
          <label>
            Name:
            <input type="text" formControlName="consentBy">
          </label>
          <label>
            Date:
            <input type="text" formControlName="consentDate">
          </label>
        </div>
        </form>
    

After submission, the date value needs to be formatted. Here is the relevant code snippet:

 get pfc() {
    return this.participantForm.controls;
  }
this.participantForm.patchValue({
            consent: {
              consentDate : moment(this.pfc.consent.consentDate.value, "DD-MMM-YYY HH:mm").format(
                "DD-MMM-YYYY HH:mm")
              }
          });
      

An error occurs:

 ERROR TypeError: Cannot read property 'consentDate' of undefined.
     
     

The issue lies in consent being undefined. How can I rectify this and update the form value?

Answer №1

To retrieve the desired value, you can either extract it directly from the form or retrieve it as a JSON object and then use it accordingly. It appears that the issue lies in correctly assigning a value to 'pfc'.

const formData = this.participantForm.getRawValue();
this.participantForm.patchValue({
            consent: {
              consentDate : moment(formData.consent.consentDate, "DD-MMM-YYY HH:mm").format(
                "DD-MMM-YYYY HH:mm")
              }
          });

Answer №2

To retrieve the form value, you can use the code snippet below:

this.participantForm.patchValue({
            consent: {
              consentDate : moment(this.pfc.get("consent").get("consentDate").value, "DD-MMM-YYY HH:mm").format(
                "DD-MMM-YYYY HH:mm")
              }
          });

Answer №3

When trying to access

this.pfc.consent.consentDate.value
, keep in mind that this.pfc may not directly map to a formgroup and could lead to an undefined field. To avoid this error, make sure to properly access the value using either:

this.pfc.value.consent.consentDate

or

this.pfc.get('consent.consentDate').value

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

Creating nested Array objects in a table format in Angular 2 without using a nested table and ensuring that columns remain aligned

I'm currently working on generating a table with nested Array objects. Unfortunately, using nested tables is causing alignment issues between the header of the outer table and the columns in the inner table. Here's an example of the classes I&ap ...

Definition of generic with recursive immutability

I created a type definition to ensure immutability of types and their properties all the way down. However, when I attempt to use this with a generic type, the compiler claims that the types do not overlap, preventing me from casting an object as immutable ...

AngularMap with mapping as the value

Can I implement a Map<string, Map<string, number>> collection in my Angular project? I attempted to create and initialize the variable, but encountered an error when trying to set values. Here is an example: //define variable public players: M ...

Reactjs-ffsevents does not exist as a function

An error occurred: TypeError: fsevents is not a function. This issue is located in the FSEventsWatcher file at line 162. A new FSEventsWatcher was attempted to be created in jest-haste-map, triggering this error. The watcher creation process involved map ...

Utilizing a React hook to render and map elements in a function

Can the hook return function be assigned to a render map in React? In this example, we have the socialAuthMethodsMap map with the onClick parameter. I tried to assign the signInWithApple function from the useFirebaseAuth hook, but it violates React's ...

Navigating through pages in your IONIC 3 application: A guide to routing

I have been working on an Ionic 3 project and currently using NavController for page navigation. For example: this.navCtrl.push(DetailsPage); However, I now need to switch to Angular routing. I came across a similar query regarding Ionic 2 in this link. ...

Unable to access the correct item from local storage while a user is authenticated

I am facing an issue with retrieving the userid from local storage when a user is authenticated or logged in. The user id is not being fetched immediately upon logging in, and even when navigating from one page to another, it remains unavailable until I re ...

Click to load additional data until the list has reached its full length

<ng-container *ngFor="let item of itemList | slice:0:3"> <mat-checkbox>{{item}}</mat-checkbox> </ng-container> <div> <button id="loadMore">Load More</button> </div> I wo ...

Develop a cutting-edge Drag and Drop Functionality using the innovative Material CDK

Here is a unique link you can check out: https://stackblitz.com/angular/nabbkobrxrn?file=src/app/cdk-drag-drop-enter-predicate-example.ts. In this example, I have specific goals: I want to be able to select only one number from the "Available numbers" l ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

How can I add a clear button to the datepicker in Ionic version

Trying to implement a clear button to reset the value selected with the date picker. The code snippet below has been added to my date picker component along with corresponding TypeScript. customPickerOptionFrom = { buttons: [{ text: 'Clea ...

Issue with Angular: ngForm object does not capture selected option

Revise to clean up unnecessary code. Having trouble displaying the selected option when I print the form object to the console. It's showing as undefined. Any guidance on what might be wrong with this code would be appreciated. Let me know if more in ...

Should I use Object.assign or define class properties?

Currently in the process of developing an angular application that interacts with the twitch API. The API returns data in various formats, some of which I need to parse and save into specific classes. My main concern is understanding the potential drawbac ...

Why are the icon pictures not displaying in Angular's mat-icon-button?

Recently, I stumbled upon a snippet of code in an Angular project that caught my eye. Naturally, I decided to incorporate it into my own program: <div style="text-align:center"> <a mat-icon-button class="btn-google-plus" href="http://google.com ...

Exploring the process of dynamically updating a form based on user-selected options

I need assistance with loading an array of saved templates to be used as options in an ion-select. When an option is chosen, the form should automatically update based on the selected template. Below is the structure of my templates: export interface ...

What is the correct way to set the default function parameter as `v => v` in JavaScript?

function customFunction<T, NT extends Record<string, string | number | boolean>>( data: T, normalize?: (data: T) => NT, ) { const normalizedData = normalize ? normalize(data) : {}; return Object.keys(normalizedData); } customFuncti ...

"Encountered a type error with the authorization from the credentials provider

Challenge I find myself utilizing a lone CredentialsProvider in next-auth, but grappling with the approach to managing async authorize() alongside a customized user interface. The portrayal of the user interface within types/next-auth.d.ts reads as follo ...

The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them: List of Playlists: export default class Playlists extends Component { playlists = [ ... ]; render() { const {navigation} = th ...

Arranging JSON array in Angular 6 by specific key within the nested array

Is there a way to sort the data object based on the order numbers inside the array objects? data =[ { name:'' list:{ order :2 }, { name:'' list:{ order :1 } ] ...

You cannot access the property 'subscribe' on a void type in Angular 2

fetchNews(newsCategory : any){ this.storage.get("USER_INFO").then(result =>{ this.storage.get("sessionkey").then(tempSessionKey =>{ this.email = JSON.parse(result).email; this.newSessionKey = tempSessionKey; this.authKey =JSON.stringify("Basic ...