Encountering difficulties setting a value to a key within an Object in Angular/Typescript

I'm currently working with Angular, and I've encountered an issue while trying to assign a value to a key within my model. Here's a snippet of my code:

export class aa{
    types: bb[];
}

export interface bb{
    name: string;
    age: string;
}

In my TypeScript file, I attempted the following:

newType: bb;

initValues(){
    this.newType.name = 'Anna'; //error at this line
}

However, when running the code, I received an error stating

"cannot get property of undefined"
.

Can someone please guide me on where I might be going wrong? How do I properly assign a value to a key in Angular?

Answer №1

It seems like you've defined the type for your newType attribute, but now you'll also need to give it an initial value.

newType: bb = { name: null, age: null };

Alternatively, you can mark the properties as optional in the interface without explicitly setting them to null.

export interface bb{
    name?: string;
    age?: string;
}

newType: bb = { };

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

TypeORM issue - UnsupportedDataTypeError

Here is the entity file I'm working with, user.ts: @Entity('users') export class User { @PrimaryGeneratedColumn() id: number | undefined; @Column({ type: 'string', name: 'username', nullable: true }) username: s ...

Encountering an i18next-fetch-backend issue during the transition to Angular 11

https://i.sstatic.net/TwrBx.png Encountering problems after upgrading to Angular 11 with the i18next-fetch-backend package's index.d.ts file. How can I troubleshoot this issue and what steps should I take to resolve it? Here is a snippet from the in ...

Is there a way to incorporate timeouts when waiting for a response in Axios using Typescript?

Can someone assist me in adjusting my approach to waiting for an axios response? I'm currently sending a request to a WebService and need to wait for the response before capturing the return and calling another method. I attempted to utilize async/aw ...

Error TS2339: Cannot access attribute 'reactive_support' on interface 'LocalizedStringsMethods'

Encountering the error TS2339: Property 'reactive_support' does not exist on type 'LocalizedStringsMethods' I recently updated TypeScript from version 2.6 to 2.9, and attempted import LocalizedStrings from 'react-localization&apo ...

Share edited collection with Observer

The challenge Imagine creating an Angular service that needs to expose an Observable<number[]> to consumers: numbers: Observable<number[]>; Our requirements are: Receive the latest value upon subscription Receive the entire array every tim ...

Adjust the column width dynamically in an Ionic framework

Need help with changing the size of a Column element dynamically. <ion-col [size]="this.size" [size-xl]="this.size_xl" [size-md]="this.size_md" [size-sm]="this.size_sm" [size-xs]="this.size_xs"> Faci ...

Quote the first field when parsing a CSV

Attempting to utilize Papaparse with a large CSV file that is tab delimited The code snippet appears as follows: const fs = require('fs'); const papa = require('papaparse'); const csvFile = fs.createReadStream('mylargefile.csv&apo ...

Unable to trigger (ngModelChange) event from within a div element in Angular 2

My app.component.ts contains the following code: public sendData(data: any) { console.log(data); } The code in app.component.html looks like this: <div type="text" contenteditable="true" (ngModelChange)="sendData($event)" [innerHTML]="childS ...

Register with your Facebook account - Angular 4 Typescript

After extensive searching, I have yet to find a clear answer to my question... This is my first time delving into the world of Social Networks. I am curious to know if there are options for Facebook and Twitter sign-ins using Typescript. It seems that Go ...

Executing a Playwright test against various projects or URLs within a single test run

I've been grappling with this problem for the past few days. I've tried a few workarounds, but none of them have worked as expected. What I need is to run Playwright tests against multiple URLs. Currently, running tests in a single project works ...

Troubleshooting: Data retrieval issues in AngularFire within Ionic and Angular Application

I am encountering errors and facing issues with data retrieval in my Angular and Ionic application when using AngularFire for Firebase integration. Here is a snippet from my package.json file: "dependencies": { "@angular/common": "5.0.3", "@angul ...

Angular's innerHTML dilemma

Within my Angular service, I have implemented three methods as shown below: public loadLiveChat() { let url: string; url = this.appConfig.config.liveAgent.liveAgentScriptUrl; this.dynamicallyLoadScript(url); ...

"When a class extends another class and utilizes properties within a static property, it essentially becomes

I have been encountering challenges with generics in TypeScript for quite some time now. My current setup is as follows: First, there is a generic class defined as: class Entity { public static schema = {}; } Then, there is a class that extends the ...

The Angular component router-outlet is not recognized as a known element

I have encountered an error message: 'router-outlet' is not a known element: 1. If 'router-outlet' is an Angular component, then verify that it is part of this module. 2. If 'router-outlet' is a Web Component then add ...

Connect the checkbox value to the parent component using the control value accessor

Starting my journey with Angular, I encountered a challenge with forms. In a complex form structure, I opted to create a separate component for input and validation handling. This is how a table row looks like: <tr app-table-row-i ...

"Exploring the concepts of inheritance in Typescript

I'm seeking answers regarding inheritance in TypeScript/JavaScript. Below is my base class (express controller router): abstract class BaseCtrl { abstract model; // Get all getAll = (req, res) => { this.model.find({}, (err, docs) => ...

Updating a global variable in Ionic 3

I recently started exploring the world of Ionic, Angular, and TypeScript. I encountered a scenario where I needed to have a variable "ar: AR" accessible across all pages. To achieve this, I decided to make it a global variable by following these steps: Fi ...

Can a type be established that references a type parameter from a different line?

Exploring the Promise type with an illustration: interface Promise<T> { then<TResult1 = T, TResult2 = never>( onfulfilled?: | ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ...

Handling type errors with React Typescript MuiAccordion OnChange event handler

I'm a beginner in typescript and seeking advice on defining the type for an event handler. I have a component that utilizes material ui Accordion and triggers the handler from a container. Therefore, I need to specify the type of handleChange in my co ...

reposition content according to screen size

In my web development project, I am utilizing both bootstrap and angular to create a component that includes a menu feature. My goal is to have the menu displayed in the navbar when the screen size is large, but switch it to a dropdown menu on smaller scr ...