Error: The service object is unable to bind to ngModel in Angular 5 due to a TypeError, as it cannot read the property 'state' of undefined within Object.eval

Within my service, I have an object declared:

public caseDetails = {
partyId: '',
address: {
      state: '',
      city: '',
      zip: '',
      street: ''
    }
}

I am trying to bind these objects to input boxes. This is what works:

<input type="text" [(ngModel)]="this.serviceObj.caseDetails.partyId">

However, I am unable to do the following:

<input type="text" [(ngModel)]="this.serviceObj.caseDetails.address.state">

I can successfully bind if the object is declared in my component. However, binding to a service object is not working and results in the following error:

ERROR TypeError: Cannot read property 'state' of undefined at Object.eval [as updateDirectives]

Answer №1

Important Note: It is not recommended to bind data directly from a service object. It is better to retrieve the data from the service, store it in a local variable within the component, and then work on that data. Here's an example:

Component TypeScript file:

export class XYZComponent implements OnInit {
  dataFromService: any;
  
  constructor(public service: DataService) { }

  ngOnInit() {
    this.dataFromService = this.service.caseDetails; 
  }
}

The corresponding HTML for the component:

{{dataFromService | json}}
{{dataFromService.address.state | json}}

   <form>
       <input name='test' type="text" [(ngModel)]="dataFromService.address.state">
   </form>

No changes are needed in the Service code.


This implementation has been tested and proven successful.

Service TypeScript file:

@Injectable()
export class DataService {

  public caseDetails = {
    partyId: '',
    address: {
      state: 'mystate',
      city: '',
      zip: '',
      street: ''
    }
  };
}

Component TypeScript file:

@Component({
  selector: 'xyz',
  templateUrl: 'xyz.component.html'
})
export class XYZComponent {
  constructor(public service: DataService) { }
}

Component HTML file:

{{service.caseDetails | json}}
{{service.caseDetails.address.state | json}}

   <form>
       <input name='test' type="text" [(ngModel)]="deskService.caseDetails.address.state">
   </form>

It's important to note that instead of using this, you should use

<input type="text" [(ngModel)]="serviceObj.caseDetails.address.state">

In order for this to function properly, make sure that serviceObj is declared as public.

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

acquiring environmental variables in TypeScript for node applications

I am struggling with accessing process.env variables in my TypeScript pages. It seems to be a scope issue, which doesn't make sense to me as a beginner in TypeScript. To get my environment variables, I use a YAML file and attach them to the running p ...

Angular 14 now offers ngx-pinch-zoom for an enhanced zooming experience

Is it possible to add ngx-pinch-zoom to an Angular 14 project? I encountered a peer dependency conflict when trying to install pinch-zoom with --legacy-peer-deps, which worked in the project but failed in the ci/cd pipeline due to the conflict. I attempt ...

The observed function remains untouched

In my code, I have an if condition inside a function that looks like this: public setOption() { setTimeout(() => { if (this.isCMode && !this.quest['isCompleted']) { this.toggleOption(false); } },window['TIME ...

Function that returns an Observable<Boolean> value is null following a catch block

Why is the login status null instead of false in this method? // In the method below, I am trying to return only true or false. isLoggedIn(): Observable<boolean> { return this .loadToken() .catch(e => { this.logger ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

remove a specific element from an array

Hey there! I'm attempting to remove only the keys from an array. Here's the initial array: {everyone: "everyone", random: "random", fast response time: "fast response time", less conversations: "less conversatio ...

Executing a series of imported functions from a TypeScript module

I'm developing a program that requires importing multiple functions from a separate file and executing them all to add their return values to an expected output or data transformation. It's part of a larger project where I need these functions to ...

When defining a stripe in TypeScript using process.env.STRIPE_SECRET_KEY, an error of "string | undefined" is encountered

Every time I attempt to create a new stripe object, I encounter the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string& ...

Tips for incorporating the ternary operator in JSX of a React component while utilizing TypeScript?

I am looking to implement a conditional rendering logic in React and TypeScript, where I need to return null if a specific condition is met, otherwise render a component using a ternary operator. Here is the code snippet I currently have: {condition1 && ...

How can I monitor the amount of time a user spends on a page with Google Analytics in an Angular project?

I'm looking to implement time tracking for user interactions on my Angular application using Google Analytics. What is the most effective method to achieve this? Are there any alternative tools besides Google Analytics that offer this feature built-in ...

Cannot execute npm packages installed globally on Windows 10 machine

After installing typescript and nodemon on my Windows 10 machine using the typical npm install -g [package-name] command, I encountered a problem. When attempting to run them through the terminal, an application selector window would open prompting me to c ...

Problem with synchronizing an Angular 2 application and the Angular 2 router

Currently dealing with a complex problem related to asynchronicity within an angular 2 application. The main issue arises when trying to reload information from the backend upon app refresh in the user's browser (such as F5/refresh). The setback occu ...

Generating dynamic components in Angular relies on a string input

Imagine I have an API that provides me with the following data: { title: 'title1', type: 'FullComponent' }, { title: 'title2', type: 'HalfComponent' }, { title: 'title3', type: 'Half ...

How should trpc query calls be implemented in a Next.js application for optimal performance?

Transitioning from pure frontend React to Next.js, I am currently working on implementing trpc calls to the backend. While this is a familiar process for me, it seems that the approach I've been using may not be appropriate in this case. const [weight ...

Utilizing the validator in Vue with the setup script, TypeScript, and the composition API

While working on some code from a tutorial, I came across the challenge of implementing a validator in a similar fashion to the example provided. My task involves utilizing the script setup, typescript, and the composition API. props: { image: { ...

Problem encountered while initializing a new project using Angular-CLI version 6.1.2

After attempting to create a new Angular project using ng new angular-6-boilerplate, I encountered an issue with the latest version of angular-cli. Despite using the terminal for Windows to set up my project, an error occurred: The input for the schemat ...

Utilizing a nested interface in Typescript allows for creating more complex and

My current interface is structured like this: export interface Foo { data?: Foo; bar?: boolean; } Depending on the scenario, data is used as foo.data.bar or foo.bar. However, when implementing the above interface, I encounter the error message: Prope ...

Waiting for an async method in an Angular test: Tips and tricks

When working on an Angular application, I utilize various tools libraries and some of my code that involve: Declarations with asynchronous behavior The use of setInterval within which I do not want to wait. While attempting to implement solutions like fa ...

Failed to execute start script 'ng serve' in npm start

Let me make it clear: I'm brand new to AngularJS and pretty much any Web Technology. I consider myself a novice in the realm of Web Development. I attempted to install AngularJS, and truth be told, after numerous "Mysterious Button Clicks", I might ...

VScode has identified potential problems with modules that utilize Angular Ivy, however, this should not cause any major issues

Encountering a problem with using Angular in VSCode, where there seems to be no ngModules due to AngularIvy. The error message indicates an issue with 'CommonModule' not being recognized as an NgModule class: [{ "resource": "[...]src/app/com ...