[angular] angular2: Error: TypeError: Cannot read property '...' of undefined

I have attached the plunker of my angular2 code piece. I want to print a field from my JSON but unable to print that as initially my Object is null and it is being populated via a Promise.

This is my component file

import {Component, NgModule, OnInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

class MyData {
  xyz : MySubData;
}

class MySubData {
  name : string;
} 
@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>

      {{abc.xyz.name}}
    </div>
  `,
})
export class App implements OnInit {
  abc : MyData = null;
  constructor() {
    this.name = 'Angular2'
  }

  ngOnInit() {
    setTimeout(() => {
      this.abc = new MyData();
      this.abc.xyz = new MySubData();
      this.abc.xyz.name = "Binita";
    }, 2000);
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

When I am removing the line {{abc.xyz.name}} from my template it is running fine.

I have use set time out in my code because I am getting my data from Promise (i.e asynchronous call).

I can understand initially as abc is null, my code is unable to find abc.xyz.name. But I don't want to put any if condition to check. Because I have several property inside a JSON and it is not possible for each property to write if condition.

Earlier in angularjs 1 if abc is null then it would automatically replace it with blank string. I want to do the same thing in angular2. Please suggest.

Below is the plunker

https://plnkr.co/edit/u1NqNF0penz7OS55QmoU?p=preview

This question is related to angular angular2-template 2-way-object-databinding

The answer is


That's because abc is undefined at the moment of the template rendering. You can use safe navigation operator (?) to "protect" template until HTTP call is completed:

{{abc?.xyz?.name}}

You can read more about safe navigation operator here.

Update:

Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf directive to overcome this problem:

<div *ngIf="arr && arr.length > 0">
    {{arr[0].name}}
</div>

Read more about NgIf directive here.


Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class

  myObj:any = {
    doSomething: function () { console.log('doing something'); return 'doing something'; },
  };
  myArray:any;
  constructor() { }

  ngOnInit() {
    this.myArray = [this.myObj];
  }

You can use it in template html file as following:

<div>test-1: {{  myObj?.doSomething()}}</div>
<div>test-2: {{  myArray[0].doSomething()}}</div>
<div>test-3: {{  myArray[2]?.doSomething()}}</div>

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to angular2-template

Please add a @Pipe/@Directive/@Component annotation. Error How to truncate text in Angular2? What is let-* in Angular 2 templates? angular2: Error: TypeError: Cannot read property '...' of undefined Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release) Angular2: Cannot read property 'name' of undefined How to prevent Browser cache on Angular 2 site? Angular 2 Scroll to top on Route Change <ng-container> vs <template> Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

Examples related to 2-way-object-databinding

angular2: Error: TypeError: Cannot read property '...' of undefined Angular 2 two way binding using ngModel is not working