I created a StackBlitz demo featuring a button that, when clicked, should pass a value to the controller. In the controller, there is a function designed to assign this value to an object. However, TypeScript seems to be indicating that the object is undefined and preventing me from assigning values to its properties.
In my attempt to resolve the issue, I referred to the TypeScript Handbook's section on object types:
person: { name: string; age: number }
What I anticipated seeing in the console output was:
Button clicked!
42
{ foo: undefined; bar: undefined }
{ foo: 42; bar: true }
However, the actual output was:
Button clicked!
42
undefined
ERROR Error: cannot set property 'foo' of undefined
This deviation from expectations leaves me puzzled. Can anyone identify what might be causing this error?
The relevant code snippets are as follows:
app.component.html
<button (click)="clickMe(42)">Click me!</button>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent {
myObject: { foo: number; bar: boolean };
clickMe(value) {
console.log("Button clicked!");
console.log(value);
console.log(this.myObject);
this.myObject.foo = value;
this.myObject.bar = true;
console.log(this.myObject);
}
}