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

"Unlocking the Power of Ionic: A Guide to Detecting Status 302 URL Redirects

Trying to handle a http.post() request that results in a 302 redirect, but struggling to extract the redirected URL. Any tips on how to achieve this? Appreciate any help. ...

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

Having trouble with Angular 2 Routing and loading components?

I am facing an issue with Angular 2 where it is searching for my component in app/app/aboutus.component, but I cannot pinpoint the source of the problem. Here is my app.component.ts code: import { Component } from '@angular/core'; import { ROUT ...

The server has access to an environment variable that is not available on the client, despite being properly prefixed

In my project, I have a file named .env.local that contains three variables: NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY=pk_test_<get-your-own> MAGIC_SECRET_KEY=sk_test_<get-your-own> TOKEN_SECRET=some-secret These variables are printed out in the file ...

Tips for effectively handling Dependency Injection when interfacing with a service that requires a component

I oversee a project in Angular that follows this specific architecture: ├── media └── src ├── app │   ├── core <-- services folder inside │   ├── data │   ├── layout │  ...

What is the proper way to import the Database class from BetterSqlite3 in a TypeScript project?

I am currently working on code that utilizes better-sqlite3 and my goal is to convert it to typescript. The original javascript code includes the following relevant sections: import Database from "better-sqlite3"; /** * @param {string} filenam ...

Retrieving the value from the series object and showing it in the tooltip of a high chart with the help of Angular 4

I have successfully implemented the display of x and y values in the tooltip of a Highchart within my Angular 4 application. By utilizing the formatter function of the tooltip, I am able to achieve this functionality. The graphdata array is initially set w ...

Is it possible to invoke JavaScript code from TypeScript?

I'm struggling with calling a JavaScript file from TypeScript. After resolving one import issue and adjusting the base function for tsc recognition, I'm now stuck on recognizing a declared function prototype in the JavaScript file. Although I ha ...

Verify if the page was generated as a regular Page or a modal page

Within the UpgradePage, I have a scenario where I want to navigate to the same page either through the side menu or as a modal page using push/setRoot. Q: The method upgradeLater() is where I need to make a decision on whether to redirect to another page, ...

Custom JavaScript files are not recognized by Angular 4 pages unless the page is manually refreshed

I am facing an issue with my custom JavaScript files in Angular. I have imported them all in the angular-cli.json file but the pages do not recognize them unless I refresh the page after navigating from one page to another. Here is a snippet of my angular ...

The index.ngfactory.ts file threw an unexpected token error, indicating that an appropriate loader may be necessary to handle this specific file

I've spent several hours trying to troubleshoot this persistent error, exhausting all online resources for solutions. The issue arises consistently with every module of Angular Material only during the build process using --env.prod. The webpack confi ...

Dealing with a missing item in local storage in an Angular application

When working with local storage, I have a function that saves certain values and another method that reloads these values. However, what is the best approach to handle missing items in the local storage? This could happen if a user deletes an item or if it ...

How is it possible to utilize type assertions with literals like `false`?

When working in TypeScript, I came across an interesting observation when compiling the following code: const x = true as false; Surprisingly, this direct assertion is valid, creating a constant x with the value true and type false. This differs from the ...

Checking if the Cursor is Currently Positioned on a Chart Element in Word Addin/OfficeJS

I am looking for a way to determine if the document cursor is currently positioned inside of a Chart element using the Microsoft Word API. My current application can successfully insert text, but when I attempt to insert text into the Chart title, it ends ...

Is it possible to compress an Array comprised of nested Arrays?

I am working on a function that takes in a specific type structure: type Input = [Array<string>, Array<number>, Array<boolean>]; It then transforms and outputs the data in this format: Array<[string, number, boolean]> This essenti ...

Get a single object from an array with .single method provided by @ngrx

Seeking to retrieve an Observable containing a single object from an array of objects in my store. I aim to utilize the .single operator, which should throw an exception if there is not exactly 1 object present. However, I'm struggling with this as my ...

What is the best way to increase the height of an image beyond the limits of its container, causing it to overlap with other elements

My challenge involves creating a horizontal scrolling list of movie posters. I want the posters to grow in size when hovered over, expanding outside of their container and overlapping other elements. I attempted to use 'position: absolute' on the ...

Ways to attach an event listener to a useRef hook within a useEffect hook

As I work on creating a custom hook, I am faced with the task of adding an event listener to a ref. However, I am uncertain about how to properly handle cleaning up the event listener since both listRef and listRef.current may potentially be null: const ...

Angular Validators.pattern() does not seem to function properly, despite yielding successful results in online regex testers

I have developed a regex pattern on Regex101.com and thoroughly tested it. However, when I applied it to my FormControl Validators.pattern method, it is exhibiting unexpected behavior. This regex pattern is meant for validating the Width input of a packag ...

Angular2 module encounters failure when trying to inject InjectionToken using @Inject()

I've recently encountered an issue with InjectionToken that is declared within a module. import {InjectionToken, NgModule} from '@angular/core'; import {SampleComponent} from './sample.component'; export let SOME_TOKEN = new Inje ...