2

I want to loop through each element by its class for setting new value in the src attribute. below is the jquery code, how can i rewrite in typescript in angular

$(".image").each(function () {
    $(this).attr("src","http://xxx/xxx.png");
});
Vishnudas
  • 229
  • 2
  • 10
  • What's the issue you are having? – dcg Mar 27 '19 at 07:36
  • 1
    You wouldn't. Use property binding to bind to the `src` element of each image directly. – jBuchholz Mar 27 '19 at 07:38
  • 1
    You generally don't modify the DOM in Angular. You modify the model which is the single point of truth, and the view is modified accordingly. You need to learn how to do things the Angular way, and not the jQuery way. – JB Nizet Mar 27 '19 at 07:39
  • In my case iam dynamically appending html to template. After that i want to change the src of element .Is there any way to do it in typescript @JBNizet – Vishnudas Mar 27 '19 at 08:17

2 Answers2

1

Try to use opposite approach - store collection inside component and iterate inside view:

component.ts

public urls = ['url1', 'url2'];

component.html

<img *ngFor="let url of urls" [src]="url">

If you change something in your urls now it will affect the view.

Patryk Uszyński
  • 1,069
  • 1
  • 12
  • 20
  • In my case i am dynamically appending html to template. After that i want to change the src of element .Is there any way to do it in typescript @Patryk Uszyński – Vishnudas Mar 27 '19 at 08:19
  • @Vishnudas you can start with empty `urls` array. When you dynamically push new item it will be rendered. – Patryk Uszyński Mar 27 '19 at 08:25
1

I think this may help you:

Array.from(document.getElementsByClassName("image")).forEach(function(item) {
    var image_link=item.getAttribute('href');
    item.setAttribute('src',"path");
});

Please check this for details: For loop for HTMLCollection elements

Anoop Sankar
  • 619
  • 5
  • 16