1

I have service which return objects to component, and iterate objects inside template, some of the properties might be null and breaks the js how can I prevent this to happen ?

template:

<table id="simple-table" class="table table-striped table-bordered table-hover">
 <caption>Table of artists</caption>
    <thead>
        <tr>
            <th>id</th>
            <th>name</th>
            <th>image</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let artist of artists">

            <td>{{artist.id}}</td>
            <td>{{artist.name}}</td>
            <td><img class="img-circle" style="width:100%" src="{{artist.images[0].url}}"></td>
        </tr>
    </tbody>
</table>

artist.images[0].url throws "annot read property 'url' of undefined" error since images is null how can I fix in single line with cascade conditions ?

7
  • 1
    What does console.log(this.artists) print instead of console.log(data)? Commented Dec 2, 2016 at 10:07
  • What does <div>{{artists | json}}</div> display? Commented Dec 2, 2016 at 10:09
  • @echonax its sam, i set breakpoint in subscription function and check the value of artist property, all objects loaded, nothing suspicious looking in there Commented Dec 2, 2016 at 10:10
  • @GünterZöchbauer nothing, I think something wrong with binding here.. Commented Dec 2, 2016 at 10:13
  • 1
    Can you try adding private cdRef:ChangeDetectorRef to constructor parameters and call this.cdRef.detectChanges() after this.artists = ...;? Commented Dec 2, 2016 at 10:16

1 Answer 1

3

You can safe-navigation ?. instead of . but not with [].

This should work

artists?.images && artist.images[0]?.url

or alternatively

<table *ngIf="artists.images.length" ...
Sign up to request clarification or add additional context in comments.

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.