1

In my angular project, I have the following:

TS

this.storage.get(item_section).then((value) => {
    this.item= value;
    console.log(this.item); //The console log gives `["name","item","size"]`
    console.log(this.item[1]); //Gives `item` as the console log
});

HTML

<div class="something">{{item}}</div> //Displays "name,item,size"
<div class="something">{{item[1]}}</div> //Gets Undefined error

If I can define the this.item and get results for {{item}}, how come I get undefined error for {{item[1]}}?

I am little confused to how to fix this

4
  • 2
    Your code asynchronous. Just think about it Commented Jun 20, 2017 at 5:16
  • 2
    item is only assignable when the async operation finishes. You can use something like this in component: this.item = this.storage.get(item_section); and in template: <ng-container *ngIf="item | async as resolvedItem"><div class="something">{{resolvedItem[1]}}</div></ng-container> Commented Jun 20, 2017 at 5:17
  • If you want to know why it happens, you can see this question. Commented Jun 20, 2017 at 5:25
  • @developer033 Thank you! I was looking through some forums to see why it was the case. Much appreciated guys!=) Commented Jun 20, 2017 at 5:27

4 Answers 4

4

Your operation is async, so you need to wait for the item to be loaded to access the second element of the item. You can use *ngIf to achieve it.

<div class="something" *ngIf="item">{{item[1]}}</div> 
Sign up to request clarification or add additional context in comments.

1 Comment

"...to be loaded to access the first element..." In fact, he doesn't want to access the first element, but the second :)
3

Simply add a '?' next to your array item, it should work fine. Refer Safe Navigation Operator for displaying data if exists.

8 Comments

It's called Safe Navigation Operator.
Hmm, I just remembered that the Safe Navigation Operator doesn't support this kind of situation (I mean bracket notation)... if you try: item?[1] you'll get a "Template parse errors...".
Yes, I just checked it out myself. It throws a template parse error.
@developer033 I think a ternary operator would work just fine in this case :) item[1]?item[1]:''
No, it won't work also, it still produces error, you can do: {{ item ? item[1] : '' }}.
|
1

It should work for the static data, it works fine here.

Check the DEMO

Alternatively since your code is asynchronous, you can try this,

<div class="something">{{item && item[0]}}

Comments

1

please try below:

<div class="something" *ngFor="let itm of item | async">{{itm}}</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.