2

I have the following code in my .ts file.

yourInfoData: IYourInfoData; //IYourInfoData is my constructor

getYourInfoData() {
  $this = this;
  $this.yourInfoData = yourInfoDataResponse; //yourInfoDataResponseis my response from service.
}

yourInfoDataResponsestructure is as follows:

yourInfoDataResponse{
  "firstName" : "Xyz",
  "lastName" : "Abc"
}

Can I access this.yourInfoData directly to bind with html input value as below :

<input type="text" [(ngModel)]="yourInfoData.firstName">

Doing so, I am getting an error

Cannot find firstName of undefined.

Can someone point to me what am I missing here. Or, is there other way to achieve this.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Prashanth
  • 1,235
  • 2
  • 12
  • 13

1 Answers1

5

If you get the JSON from a service it's probably async and arrives with a delay

When Angular tries to resolve the template bindings while the data is not available it fails.

You can use the safe-navigation (Elvis) operator to avoid the error

<!-- doesn't work 
  <input type="text" [(ngModel)]="yourInfoData?.firstName">
-->

See this issue https://github.com/angular/angular/issues/7697

<input type="text" [ngModel]="yourInfoData?.firstName"
                   (ngModelChange)="yourInfoData.firstName=$event">

or if it can happen that the model changes before yourInfoData is set

<input type="text" [ngModel]="yourInfoData?.firstName"
                   (ngModelChange)="yourInfoData ? yourInfoData.firstName=$event : null">

this would also work

<input type="text" *ngIf="yourInfoData" [(ngModel)]="yourInfoData.firstName">

but it wouldn't display the input unless yourInfoData is set.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Tried that too. Received this error in the console : zone.js:461 Unhandled Promise rejection: Template parse errors: Parser Error: The '?.' operator cannot be used in the assignment at column 25 in [yourInfoData?.fisrtName=$event] in YourInfoComponent@6:47 ("

    ][(ngModel)]="yourInfoData?.fisrtName">

    "): YourInfoComponent@6:47 ; Zone: angular ; Task: Promise.then ; Value:

    – Prashanth Jun 10 '16 at 08:33
  • You are right. Sorry I didn't pay attention. I updated my answer. – Günter Zöchbauer Jun 10 '16 at 08:41
  • Works like magic. Thanks a lot Günter Zöchbauer. Solves my issue. – Prashanth Jun 10 '16 at 08:53