David Aguirre
David Aguirre

Reputation: 1410

Angular 2 Expression has changed after it was checked. Error with Dynamic Image Src

I have a loop that creates a list of events.

<ng-container *ngFor="let event of venueEvents">
    <div class="event-card">
        <div class="event-image">
            <img src={{getRandomImage()}}>
        </div>
        <div class="event-details">
            <p class="event-title">{{event.name}}</p>
            <p class="event-time">{{event.nextOccursOn | date}}</p>
        </div>
    </div>     
</ng-container>

As you can see the image is a dynamic image that is populated with a function.

getRandomImage() {
    let baseImageLink = "http://lorempixel.com/640/480/",
        linkKey = {
            '1': 'nature',
            '2': 'sports',
            '3': 'cat',
            '4': 'nightlife',
            '5': 'food'
        },
        randomNumber = Math.floor((Math.random() * 5) + 1);
    return baseImageLink + linkKey[randomNumber];
}

This is working as expected, but the console shows an error.

 EXCEPTION: Error in ./VenueDetailComponent class VenueDetailComponent - inline template:64:21 caused by: Expression has changed after it was checked. Previous value: 'http://lorempixel.com/640/480/sports'. Current value: 'http://lorempixel.com/640/480/cat'.

This is some temporary function that would never exist in the real application, but I would like to understand the problem and know how it should be solved.

Upvotes: 3

Views: 757

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657416

You get that error because you bind a method to a view that returns a different value each time its called

 <img src={{getRandomImage()}}>

Every time Angular runs change detection getRandomImage() is called, and every time a different value is returned.

You should generate the values, store them in an array and than bind to the array instead of the method directly.

Upvotes: 4

Related Questions