0

In an Angular 5 project, I have the following in:

inventory.component.ts:

  inventoryItems: any;
  constructor(private router: Router,) {
  }
  ngOnInit() {
    this.inventoryItems=[];
  }

I reference the variable like this in inventory.component.html:

<span class="indicator">{{inventoryItems.length}}</span>

The browser console is complaining about:

ERROR TypeError: Cannot read property 'length' of null

If the property is getting initialized in ngOnInit, why would it be null? It should be zero.

6
  • Why not set it as an empty array in the component definition? Commented Nov 11, 2017 at 19:55
  • If this.inventoryItems is an observable, then you could try doing {{ inventoryItems.length | async }} within the HTML. This will tell the template to wait until the observable is resolved. Commented Nov 11, 2017 at 20:00
  • Put it inside constructor this.inventoryItems=[]; Commented Nov 11, 2017 at 20:09
  • I don't think the OP is asking for a fix. The question appears to be more about why ngOnInit is not running before the template first attempts to access inventoryItems. Commented Nov 11, 2017 at 20:14
  • 1
    The code in the question doesn't explain why inventoryItems is null. Because it won't be null, and the code above won't throw an error. If it's an input, this should be reflected in the question. Please, provide stackoverflow.com/help/mcve that can be replicated. Commented Nov 11, 2017 at 20:57

2 Answers 2

1

Try adding *ngIf="inventoryItems"

<span *ngIf="inventoryItems" class="indicator">{{inventoryItems.length}}</span>
Sign up to request clarification or add additional context in comments.

1 Comment

This worked and the error is gone. But I don't see any output for length. It should be "0". Any idea why it isn't show anything?
1

it is null on first template initialization, because ngOnInit is called after calling first ngOnChanges, which sets the props initially. check docs

you can implemet OnChanges (and handle all props input changes manually), or you can set default value like this for example inventoryItems: any[] = [];

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.