How to display images dynamically at the angle with ngFor directive

Asked

Viewed 169 times

1

Well, I’m trying to create a photo slider, which I need to leave dynamic so I don’t have to endlessly copy and paste a few snippets.

I have an array with the names of the images:

array: any = [{id: 1, nome: 'imagem1'}, {id: 2, nome: 'imagem2'} ];

I am displaying them in html with angled for loop (7)

<span *ngFor="let item of array ">
  <img class="slides" [src]="root + item.nome + '.jpg'">
</span>

When trying to catch the tag img const slide: any = document.getElementsByClassName('slides'); (that returns an Htmlcollection) I always have a length 0, I think because the angular cannot wait ngFor (I’m not sure)

inserir a descrição da imagem aqui

In case I need this Collection to make the images appear according to my array.

Someone would have a notion or some alternative (even if completely different in the code)?

  • It is very strange that there, because independent if the images are with the correct path or not (which would cause an error in the console of 404 - not found), the ngFor is traversing an array with size 2, so obligatorily, two tags would have to be created img html. There must be something else there that you haven’t posted!

  • @Leandrade, the path is correct (this would be my 'root' variable above), because I do without ngFor works, but then I would have to copy and paste to a new image. The example I took was the W3 (https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_self) that in this case, it goes through the array since it has a collection in the template (3 img tags) and I only have one. So it refers to ' x[slideIndex-1]', but I don’t have items in this array, ACHO pq in my template I only have an img tag and ngFor doesn’t finish "run" to deliver the 3 img to . ts

  • I do not know what is happening there in your code, I tested it here and it worked normal, rendered the images in html and gave a console.log(slides) in ngOnInit() and returned Htmlcollection with size 2 normally.

  • So @Leandrade found the problem. There were two: One because I was setting the value of the array in onInit and in turn was setting at a different time from the template (obvious) I decided setting the value before. And the second was to set the style.display, as in the W3 example. As I needed the values I picked up inside a function, I ran this function inside the Afterviewinit, so I could get it when I really had the value of the full imgs... Thank you very much for the force, I got it after debugging the beginning as Oce said he got it... Thanks!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.