Angular encountered an ERROR of type TypeError where it cannot access properties that are undefined when trying to read the 'title'

I designed a form and I am trying to save the information entered. However, when I attempt to use the save method, an error keeps popping up. How can I troubleshoot this issue and successfully save the data from the form?

Answer №1

My recommendation is to avoid using both formControlName and ngModel on the same input tag. Instead, use formControlName only by assigning a name linked to a FormGroup.

Below is an example of how you can achieve this:

app.component.html

<form [formGroup]="postForm">
    <input type="text" formControlName="title">
    <button (click)="submit()">Save</button>
</form>

app.component.ts

export class AppComponent implements OnInit {
  
  postForm: FormGroup;
  
  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.createPostForm();
  }

  submit(): void {
    for (const i in this.postForm.controls) {
      this.postForm.controls[i].markAsDirty();
      this.postForm.controls[i].updateValueAndValidity();
    }
    if (this.postForm.valid) {
        // Submit to server... 
    }
  }

  /** Create postform instance */
  createPostForm(): void {
    this.postForm = this.fb.group({
      title: [null, Validators.required],
      content: '',
    
    });
  }

}

In addition, I noticed that you are attempting to check if a post already exists before creating a new one or updating details. My suggestion is to implement this logic on the backend using options like UpdateOrCreate in your database. By passing a post id into your params or body, you can easily determine whether to create a new post or update an existing one. This approach will improve the maintainability of your code.

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 a mechanism for automatic refreshing of JWT tokens in a Spring Boot and Angular application

I am working with Spring Boot and storing JWT tokens in httpOnly cookies. How can I implement automatic token refresh using the existing refresh tokens method on the backend? ...

React | Utilizing ForwardedRefs with React Components

I'm currently working on a React project where I am creating a custom component that needs to be exported using forwardedRef. However, as I attempt to do this, an error keeps popping up: error This is the code snippet causing the issue: export inter ...

Leverage the Nuxeo client SDK with Angular 6 for seamless integration with RESTClient in

Looking to integrate the Nuxeo ClientSdk with my Angular 6 client to consume its REST API, but facing issues due to the lack of typescript definitions for this JavaScript package. Tried importing the library into my project using the following code snippe ...

Step-by-step guide to designing a leaflet map using Angular Formly

I am faced with a challenge to incorporate a leaflet map into an angular form using formly, and being new to this formly framework is making it difficult for me. Previously, I was able to integrate the map with regular HTML in angular as shown below: map ...

Serialising and deserialising TypeScript types in local storage

I'm currently working on a Typescript application where I store objects using local storage for development purposes. However, I've run into some trouble with deserialization. Specifically, I have an object called meeting of type MeetingModel: ...

Encountering a type error when attempting to assign an interface to a property

In my Angular project, I am working with typescript and trying to assign the IInfoPage interface to some data. export interface IInfoPage { href: string; icon: string; routing: boolean; order: number; styleType: string; ...

The Angular array stays undefined when JSON data is being passed

I am facing an issue with my API that provides JSON data related to football matches. Even after passing this data to the frontend (angular), I am encountering a problem where the array remains undefined. JSON Data: "match_id":"194200", "country_id":"41" ...

Use the ngFor directive to iterate over the most recently created array from the parent ng

I am looking to link material tabs with ngFor to generate arrays for child ngFor. Let's start from the beginning: <mat-tab-group> <mat-tab *ngFor="let tab of asyncTabs "> <ng-template mat-tab-label>{{tab.label}}</ng-template ...

Firestore TimeStamp.fromDate is not based on UTC timing

Does anyone have a solution for persisting UTC Timestamps in Firestore? In my Angular application, when I convert today's date to a Timestamp using the code below, it stores as UTC+2 (due to summer time in Switzerland). import {firebase} from ' ...

Ways to resolve NPM dependency conflicts

Attempting to set up all the necessary npm packages for the AWS sample demo found at https://github.com/aws-samples/amazon-chime-sdk-classroom-demo on my laptop has been a bit challenging. Every time I try to run npm install I can't help but wonder i ...

How can I retrieve image files from locations outside the Angular 5 app or assets directory?

One of the features in my app allows users to upload images. I recently learned that it's best practice to store these image files outside of the app or assets folder since those folders are compiled. Here is a snapshot of my app's folder structu ...

There appears to be an issue with the headers not being

Whenever I use HttpClient to send a request, I make sure to set the necessary headers. However, upon checking the network tab in Chrome, I noticed that these headers are not being properly set. Here is the code snippet: request(url: string, method: strin ...

JavaScript: exporting everything from ... causing excessive bloat in the build file

After building my react-app with create-react-app, I noticed a decline in performance. Here is the structure of my project: /store actions.ts reducers.ts /module1 module1.actions.ts module1.reducers.ts /moduleN moduleN.actions.ts m ...

Problems arising from the layout of the PrimeNG DataView component when used alongside Prime

I've been working with a PrimeNG DataView component that requires the use of PrimeFlex's flex grid CSS classes to set up the grid structure. One of their examples includes the following instructions: When in grid mode, the ng-template element ...

Navigate smoothly in Angular 4 with Spring Boot without the need for hash codes in the URL routing

Here is the scenario I am facing: I am currently using Spring Boot with Angular 4 I generate a build file using angular-cli and place it under the resource -- static folder. When I run my pom.xml, all the files in the static folder are copied to target ...

Error: The specified function in the schema is not valid for the current operation mode

I'm facing an issue with validating a material ui form using Formik and Yup. The error keeps popping up. This is the schema I imported from another file: export const validationSchema = Yup.object({ email: Yup.string() .email('Invalid Ema ...

Unlocking Global Opportunities with Stencil for Internationalization

Hi there, I've been attempting to implement Internationalization in my stencil project but unfortunately, it's not working as expected. I'm not sure what's causing the issue, and all I'm seeing is a 404 error. I followed these arti ...

How does Vue compare to Angular in terms of components?

Is there a simple way to render dynamic components in Angular similar to how it's done in Vue? In Vue, rendering a dynamic component is as easy as this: <component v-bind:is="'componentX'"></component> How can this be ...

The Angular Material Datepicker does not include an exported member called MatCalendarCellClassFunction

Struggling to mark specific dates on an Angular Material Datepicker view, following the instructions provided in the material documentation. The example given there works perfectly, as does the Stackblitz demo linked. Attempted to import it into my compon ...

When using React with TypeScript, there seems to be an issue where using history.push to change the URL results in rendering the 404 page instead

I have gone through all the previous answers but none of them could solve my problem. I am new to React and currently working on a personal project where I use React with TypeScript, Redux, and Material UI. For some reason, when I try to redirect from ins ...