Home > database >  How to randomly display images in angular?
How to randomly display images in angular?

Time:12-13

I have a array of images that I want them to be displayed randomly in UI.

Tried below code in typescrip, but getting error for innerHTML.
randomPic(){
    this.randomNum= Math.floor(Math.random() * this.myPix.length);
    console.log(this.randomNum)
    return  document.getElementById('myPicture').innerHTML= '<img src="' this.myPix[randomNum] '" />'; 
  }


Can somebody help me that where am I doing it wrong?

CodePudding user response:

You should not use document.getElementById in an angular context. Usually, what you want can be achieved by binding data from your component to your template (and vice versa).

import { Component } from '@angular/core';
@Component({
  selector: 'app-foobar',
  template: `
    <img [src]="myPix[randomNumber]" />
  `,
})
export class FoobarComponent {
  readonly myPix = [
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/200',
    'https://via.placeholder.com/350',
    'https://via.placeholder.com/400',
  ];

  randomNumber = Math.floor(Math.random() * this.myPix.length);
}

In this example we make use of property binding ([src]).

  • Related