By Empty_Soul


2019-01-11 11:01:42 8 Comments

I have two json files called contacts and workers. I am displaying the contacts and their assigned workers from workers JSON like this:

enter image description here

ERROR TypeError: Cannot read property 'length' of undefined

Here i am stuck with error, I am unable to find whats wrong with the code.

Stackblitz DEMO

2 comments

@Sneha Pawar 2019-01-11 11:15:02

update your function as below:

 getWorkerById(workerId) {
   if(this.workers.length > 0){
     for(let w of this.workers) {
        if(w.id === workerId) 
         return w.name;
       }
    }
 }

and add ngIf for workers

<tr *ngIf="contact.workers">
    <td>Assigned Workers</td>
    <td>
        <ul>
            <li *ngFor="let workerId of contact.workers"> 
              {{getWorkerById(workerId)}}</li>
        </ul>
    </td>
</tr>

@Pardeep Jain 2019-01-11 11:07:47

Just wrap your forLoop with condition, like this -

if (this.workers && this.workers.length) { }

Problem you are calling/Binding method with view part, and it calles every time in change detection. so in first this.workers is empty and it throws error.

Working Example

@Empty_Soul 2019-01-11 11:11:11

Sorry, you didn't made any changes in Working Example

@Pardeep Jain 2019-01-11 11:11:53

Updated stackblitz, please try again

Related Questions

Sponsored Content

2 Answered Questions

[SOLVED] Angular 7 - TypeError: Cannot read property 'filter' of undefined

22 Answered Questions

[SOLVED] Can't bind to 'ngModel' since it isn't a known property of 'input'

17 Answered Questions

[SOLVED] typescript getting error TS2304: cannot find name ' require'

2 Answered Questions

[SOLVED] Angular Cannot read property 'subscribe' of undefined

  • 2018-07-03 18:52:05
  • Cagurtay
  • 2316 View
  • 1 Score
  • 2 Answer
  • Tags:   angular

1 Answered Questions

2 Answered Questions

[SOLVED] Angular: ERROR TypeError: Cannot read property ___ of undefined

1 Answered Questions

[SOLVED] ERROR TypeError: Cannot read property 'nativeElement' of undefined

1 Answered Questions

1 Answered Questions

Sponsored Content