Having trouble associating an object with a template using ngModel?

It seems like such a simple thing to do, but for some reason I can't seem to get it right.

Here is what I have in my class:

interface Message {
  type:  string;
  email: string;
}

export class MyClass {
  public message: Message;
  public email: string;

  constructor() { }

  // ...
}

When I bind the email variable using [(ngModel)]='email', everything works fine. But when I try to bind the message with [(ngModel)]='message.email', I encounter this error:

Cannot read property 'email' of undefined.
Why does Angular fail to access my object variable?

Answer №1

To enable binding an input on one of the properties of your message property, you must first initialize it:

export class MyClass {
  public message: Message = { type: '...', email: '...'};
  public email: string;

  constructor() { }

  // ...
}

Update:

In this scenario, since Message is an interface, you cannot directly instantiate an object of this type. Instead, use a literal object expression to create an instance of type Message. TypeScript will validate that all necessary elements are included.

If you wish to create an instance of the type, define a class. Classes have representation in compiled code unlike interfaces.

Below is an example:

export class Message {
  constructor(public type: string, public email: string) {
  }
}

export class MyClass {
  public message: Message = new Message('type', 'email');
  public email: string;

  constructor() { }

  // ...
}

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

Perform TypeScript type checks exclusively on a Next.js project

In my current project using Next.js with TypeScript in a mono-repo setup, I have multiple applications under the same repository. When pushing changes to this setup, various hooks are triggered locally to ensure that the modifications meet the required sta ...

Utilizing Nativescript alongside Angular 2 and Firebase: A Comprehensive Guide

I am searching for a guide on how to integrate Angular 2 with NativeScript and Firebase backend. Does anyone have any resources or sample code they could recommend? Appreciate it. ...

Ensuring Type Safety for Collections in TypeScript

My code snippet looks like this: portfolioList: MatTableDataSource<Portfolio>; ngOnInit(): void { this.backend.getStatement().subscribe( list => { if(list as Portfolio[]) this.portfolioList = new MatTableDataSource(l ...

Typescript signals that the symbol being exported is not recognized as an exported symbol

I am working on a straightforward project $ ls -l total 32 -rw-rw-r-- 1 ocket8888 ocket8888 72 Apr 29 09:30 index.ts -rw-rw-r-- 1 ocket8888 ocket8888 105 Apr 29 09:31 main.ts drwxrwxr-x 4 ocket8888 ocket8888 4096 Apr 29 09:26 node_modules -rw-rw-r-- 1 o ...

Displaying a specific item with an icon in a list for user interaction in Ionic 3

Currently, I am working on a brand new music application. As part of my project, I have curated an extensive list of songs displayed on the homepage. My objective is to implement a feature where when a user clicks on a specific song from the list, it will ...

Validating dynamic textboxes in Angular with custom rules

Creating dynamic textboxes with *ngFor in Angular <tr *ngFor="let computer in _Computers; let i = index;"> <td>{{computer.Name}}</td><td>{{computer.Optional}}</td> <td> <input matInput [formControl] = " ...

When ng-test is executed in an Angular service, the function array.some is not found

After retrieving allUsers from the cache and initializing it, I then set the boolean value of specialUserExists based on a condition in allUsers using allUsers.some() (reference to the Array.prototype.some() method). service.ts @Injectable({ providedIn: ...

Error TS2307 - Module 'lodash' not found during build process

Latest Update I must apologize for the confusion in my previous explanation of the issue. The errors I encountered were not during the compilation of the Angular application via Gulp, but rather in the Visual Studio 'Errors List'. Fortunately, I ...

Is it possible to access ng-content components using @ViewChild?

I have utilized a card template that employs ng-content slots in the following manner: <ng-content select="card-header"></ng-content> <ng-content select="card-body"></ng-content> <ng-content></ng-c ...

Strategies for passing multiple props to a function in React using TypeScript, such as useState([]) and useState(boolean)

Dealing with API Structure { "default": [ { "id": 1, "name": "A" }, { "id": 2, "name": "B" }, { "id": 3, "name" ...

Angular's ng-select fails to select the value when generating the dynamic control

Currently, I am working on dynamically adding cities using ng-select in order to have search functionality while entering city names. For example, if I have two city names saved in a form and need to display them in separate ng-select controls when editing ...

Angular scroll directive fails to trigger

Is there a way to trigger a console.log() when the dropdown scrollbar reaches the bottom for implementing infinite scrolling or "load more" feature? Check out the screenshot https://i.sstatic.net/UmT5XvME.png In the code snippet below, I've created a ...

Error: Syntax error - there was an unexpected token '.'

An error occurred with SyntaxError: Unexpected token '.' in the file path C:\Users\bruno\OneDrive\Área de Trabalho\DEV Bruno\devapi\node\src\views\layouts\layout01.ejs while compiling ejs I ...

Error encountered: Angular2 is unable to locate the traceur module after integrating the hltv-api npm

Following a direct npm install of the hltv-api package, I attempted to import it into my component.ts file with the following code: import { getNews, getResults } from 'hltv-api'; I then configured my systemjs.config.js fi ...

Invoke a shared function within multiple component HTML files when an onchange event is triggered by a universal service

Hello there, I am currently working with angular 11. In my project, I have three components named C1, C2, and C3. These components do not have a parent-child relationship but they all share a common method called F1. Right now, F1 is declared in each compo ...

Difficulty in toggling the visibility of the react-date-range picker package when selecting a date

I need assistance with a problem I'm facing. I am having trouble hiding and showing the react-date-range picker upon date selection. The issue is related to a package that I am using for date range selection. You can find the package link here - https ...

Debugging is not possible for applications running on an Android device with Ionic 2

Instructions to replicate the issue: 1. Begin by creating a new project from the following repository: https://github.com/driftyco/ionic-starter-super 2. Execute the command `ionic run android` 3. Utilize chrome://inspect for debugging purposes The ...

Angular elements nested within each other are causing the ExpressionChangedAfterItHasBeenCheckedError

After conducting thorough research on this issue, I am now uncertain whether it is a bug or an error in my implementation. The problem arises with an element that utilizes a service to retrieve data and then passes it on to a child element. However, upon ...

A guide on setting a default constructor as a parameter in TypeScript

Through collaboration with a fellow coder on StackOverflow, I have mastered the art of specifying a constructor as an argument to a class: type GenericConstructor<T> = { new(): T; } class MyClass<T> { subclass: T; constructor( SubClas ...

Angular/NX - Element 'Component' is unrecognized, despite being imported within the module

Encountering the following issue: 'apocaloot-building' is showing as an unknown element: If 'apocaloot-building' is supposed to be an Angular component, please ensure that it is included in this module. The component in question is ...