Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle image src on click

Hi angular community !

I've got an img who's also a button an I would like to change the button/img as following "each time it's clicked show img "arrow_up" , maybe ngClass changing the css?

My button is an arrow down and each time he is clicked I would like it show an arrow up instead like in this website for exemple Angular Blogspot (if you see the blog archive on right, if you click on it the boutton changed..very common thing)

I provide an exemple with [hidden] but maybe there's a elegantest way to do the job:

html:

<img src="./arrow_down_black.png" type="button"
(click)="toggleChild()"/>
<img [hidden]=""showVar" src="./arrow_up_black.png" type="button"(click)="toggleChild()"/>
   <my-child [showMePartially]="showVar"></my-child>

ts:

clickMe() {
   this.showVar = !this.showVar;
}
like image 425
Emile Cantero Avatar asked Jun 16 '26 21:06

Emile Cantero


2 Answers

Use an expression to display the correct image.

<img src="{{ showVar ? './arrow_down_black.png' : './arrow_up_black.png'}}" 
     type="button" (click)="toggleChild()"/>

     <my-child [showMePartially]="showVar"></my-child>

.. and in your component ts file,

toggleChild() {
   this.showVar = !this.showVar;
}
like image 104
Faisal Avatar answered Jun 19 '26 12:06

Faisal


I think binding your img css class to the [ngClass] directive will do the job more elegant way.

<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">

NgClass directive example

like image 29
Krzysztof Łach Avatar answered Jun 19 '26 10:06

Krzysztof Łach