angular2: Error: TypeError: Cannot read property '…' of undefined

后端 未结 2 892
长情又很酷
长情又很酷 2020-11-22 14:34

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

相关标签:
2条回答
  • 2020-11-22 15:00

    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>
    
    0 讨论(0)
  • 2020-11-22 15:01

    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.

    0 讨论(0)
提交回复
热议问题