Issue
I have rendered multiple images using tag. I want to change the background color of image when it is clicked. But when I click on one image, the color of all the images changed.
Here is my code. I am working in Angular.
html
<img
[src]="data.Url" alt="image"
(click)="_upload(data.Url)"
[ngClass]="{'green' : toggle, 'red': !toggle}"
>
ts
inside my function
this.toggle = !this.toggle;
this.status = this.toggle ? 'Enable' : 'Disable';
Solution
For rendering multiple html elements, I assume you are using the ngFor
directive, so you could use the index
for giving each element a different css
class.
For example:
HTML
<div *ngFor="let option of options; let i = index">
<img
[src]="option.Url"
(click)="_upload(option.Url, i)"
[class.selected]="i === indexSelected" <!--apply the selected css class if condition is TRUE-->
>
</div>
css
.selected {
background-color: green;
}
ts
...
export class YourComponent {
indexSelected: number = -1;
_upload(url: string, index: number) {
// ...
this.indexSelected = index;
}
}
Answered By - Andres2142
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.