Emile Cantero
Emile Cantero

Reputation: 2053

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;
}

Upvotes: 3

Views: 4278

Answers (2)

FAISAL
FAISAL

Reputation: 34673

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;
}

Upvotes: 5

Krzysztof Lach
Krzysztof Lach

Reputation: 1380

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

Upvotes: 2

Related Questions