0

I want to render some data in loop:

  <div *ngFor="let data of parameters.items.tableConfig.nodes">
    <table-item [data]=data></table-item>
  </div>

But data

And I have error:

EXCEPTION: Error in ./TableWidgetComponent class TableWidgetComponent - inline template:7:17 caused by: Cannot read property 'nodes' of undefined

How I can wait before data come, and then render view?

*ngIf="parameters && parameters.items.tableConfig.nodes" does not helps me.

2
  • parameters.items property tableConfig is undefined Commented Mar 6, 2017 at 12:22
  • Provide some more information e.g. interface for parameters model. Are we accessing parameters asynchronously? Commented Mar 6, 2017 at 12:23

2 Answers 2

2

Use this

<div *ngFor="let data of parameters?.items?.tableConfig?.nodes">
    <table-item [data]=data></table-item>
  </div>

by using elevis operator (?) [also called safe navigation operator] it will prevent angular to throw error , beneficial in case where data is coming asynchronously like in your case

Here is detailed information about this

https://angular.io/docs/ts/latest/guide/template-syntax.html#!#safe-navigation-operator

Sign up to request clarification or add additional context in comments.

2 Comments

Cool. It works. But can you share with me link with full explanation of this.
check my Update with link @MaxKarpovets
1

Given you say 'How I can wait before data come,..', I take the data comes from an asynchronous call. So either an Observable or a Promise. You have a number of options here;

Add an if-condition around the actual loop.

<div *ngIf="parameters.items.tableConfig">...</div>

Use the safe navigation operator (?.) to guard against undefined and null.

<div *ngFor="let data of parameters.items.tableConfig?.nodes">
   <table-item [data]=data></table-item>
</div>

Use the async pipe.

It accepts a Promise or Observable and updates the view with the response data when the Promise is resolved or when the Observable emits a new value.

export class MyComponent {
   nodePromise: Promise<Node>; // e.g. with Promise.
}

<div *ngFor="let data of nodePromise | async">
   <table-item [data]=data></table-item>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.