Angular | The property ''XXX'' is undefined and cannot be read

There were 2 model.ts files utilized in this scenario.

The first one is profile.model.ts

export interface Profile {
    username: string;
    nickname: string;
    image: string;
  }


'The second one, comment.model.ts' makes use of 'profile.model.ts'.

In comment.model.ts

import { Profile } from '.';

export interface Comment {
  author: Profile;
  content: string;
  creatat?: Date;
}


Now for the comment.component.ts file

...
export class CommentComponent implements DoCheck {
  ...
  content: string;      // Retrieve value from ngModel in comment.component.html
  comments: Comment;    // Pertains to comment.model.ts
}
...

  addComment() {
    this.comments.author.nickname = 'Test Nickname';
    this.comments = {
      content: this.content
    };
    ...
  }


Upon running the addComment(), an error occurred as follows:

ERROR TypeError: Cannot read property 'author' of undefined

What could be causing this issue?

Appreciate your guidance and suggestions in advance.

Answer №1

To properly set up your comments property, you must initialize it. Currently, you have only defined the type of the property as Comment.

Since properties in the Profile are mandatory, you must assign explicit null values to them.

comments: Comment = { 
   author: {  
      username: null,
      nickname: null,
      image: null,
   }, 
   content: null 
}

Alternatively, you can make these properties optional by adding a ? after their names.

export interface Profile {
    username?: string;
    nickname?: string;
    image?: string;
}

...

export interface Comment {
  author?: Profile;
  content?: string;
  createdAt?: Date;
}

You should then initialize the comment like this:

comments: Comment = { 
   author: { } 
}

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

When using Typescript type aliases, make sure to let Intellisense display the alias name instead of the source

Take a look at this brief code snippet type A = number; declare function f(): A; const a = f(); // `a` is number, not A What could be the reason for TS displaying a: number instead of a: A? ...

Is there a way to retrieve a JSON object representing a Typescript object from the Monaco Editor?

Issue: I am in need of assistance to convert a typescript model that utilizes intellisense from extraLibs (an option in the monaco editor) into a JSON object. This JSON object will then be sent to an API for processing. Here is the code snippet that you c ...

Obtaining the value of dynamic checkboxes in Ionic 2

My goal is to populate checkboxes from a database and allow users to complete the checkbox form before submitting it back to the database. However, I am struggling to capture the values of dynamically populated checkboxes in my code snippet below. expor ...

Checkbox selection can alternate based on conditions for formgroup controls

My FormGroup named 'fruits' has been set up fruits: FormGroup = formBuilder.group({ numberOfFruits: [0,Validators.min(0)], apple: false, mangoes: false }); Here is the corresponding HTML code: <div formGroupName ...

Unable to ensure accessibility for the angular popup (modal/dialog) as the focus remains on the button that triggers the popup

Striving to ensure my website is accessible to all users has been a primary goal of mine, but I am encountering difficulties with popups and the forms contained within them. When I interact with <a id="login_btn" role="button"> t ...

Display error messages upon submitting the form

I am currently working on an Angular 6 Form with validation. My main goal is to display error messages only after the form has been submitted. It is crucial that these messages remain constant while the user types in the input field. For instance, if a use ...

A guide on utilizing Google fonts within an Angular 4 project by hosting them locally instead of importing them

Currently, I have been including google font urls in my angular 4 project scss file as shown below: @import url('https://fonts.googleapis.com/css?family=Open+Sans:400,700'); @import url('https://fonts.googleapis.com/css?family=Oswald:400,60 ...

When item.id matches group.id within the ngFor loop, a conditional statement is triggered

Creating nested columns with matching ids using ngFor seems like a challenge. How can I achieve this? Imagine having an object structured like this: columnNames = [ {id: 0, name: 'Opened'}, {id: 1, name: 'Responded'}, {id: ...

Create a versatile and abstract Observable function in Angular 6

Currently developing an angular 6 application where I need to retrieve and display a list of users from an API on every page. I have created a function that is functioning perfectly: listUsers() { let result = this.http.get('xyz.com/api/users&a ...

Issue with Angular 6 Animation not showing up

Looking to incorporate an animation spinner into my Angular app Found this spinner example: https://codepen.io/z-/pen/OPzNLz spinner.component.html import { Component, OnInit } from '@angular/core'; @Component({ selecto ...

How can I send a POST request in TypeScript?

I am new to Angular 9 and facing an issue with headers in my post request. The error message says: Unnecessarily quoted property 'Authorization' found. What does this mean? What is it asking for? How can I resolve it? serviceName.service.ts: exp ...

Angular ngx-translate: Responding to language change event

Is it possible to detect the change in the "current language" using the ngx-translate library? Which JavaScript event should I use to accomplish this task? To clarify, please refer to this straightforward example: https://stackblitz.com/edit/github-yvbmgu ...

utilizing type predictors in brand merging

For hours now, I've been struggling with a small problem that seems to have no solution in sight. I wonder if someone with a sharper mind could offer me some guidance? The method I'm using returns a predicate: this is xxx. This method is then us ...

What is the best way to store a logged-in user's email in a React

I have implemented a login API and I would like to save the email of the logged-in user in the state or another variable, so that I can display it in the header after successful login. The user's email is located in the data.email. The following code ...

Solving the issue of "/node_modules/angular2/bundles/angular2.dev.js Not Found (404)"

I recently finished reading ngbook2 and decided to dive into creating a hello-world application in Angular 2. However, I encountered the following error 404: GET /node_modules/angular2/bundles/angular2.dev.js 404 5.460 ms - 58 Here's a snippet from ...

issue with mat-select in a dialog not functionering correctly

In my current project, I am working on implementing a feature that requires the user to select an option from a drop-down menu and confirm their choice by clicking an "OK" button. To achieve this functionality, I am utilizing Angular Material. However, I h ...

Utilizing Async/Await with Node.js for Seamless MySQL Integration

I have encountered two main issues. Implementing Async/Await in database queries Handling environment variables in pool configurations I am currently using TypeScript with Node.js and Express, and I have installed promise-mysql. However, I am open to usi ...

Is it possible to enable typescript to build in watch mode with eslint integrated?

Can this be achieved without relying on webpack or other bundlers? Alternatively, is the only solution to have two separate consoles - one for building and another for linting? ...

During the installation of npm in my angular project directory, an error occurred

Encountered an error while installing packages (npm)...npm ERR! code ERR_SOCKET_TIMEOUT npm ERR! errno ERR_SOCKET_TIMEOUT npm ERR! network Received an invalid response when trying to fetch https://registry.npmjs.org/@babel%2fplugin-proposal-nullish-coalesc ...

How about a form of communication?

I'm currently diving into Angular2 and have a question regarding ngStyle. Let's take a look at the following code snippet: <div> <span [ngStyle]="{color: 'red'}" [style.font-size.px]="fontSize"> red text </span&g ...