Search code examples
htmlionic-frameworkionic3angular-ng-if

Add ng-if to an image in html


So, I have two images on a html page in my ionic project, and I want the second image to show up when the first one is clicked. Therefore i added a onClick to my image like:

<img  src="path"
    alt="foo" 
    style="foo;
    width:foo;
    left:30%;top:30%" 
    class = "foo"
    onclick="ng-model='bar'" >

And the second image

<img  src="path" 
    *ngIf="bar">

But it is not working that way. Is it the wrong way? I tried it that way to avoid additional javascript.


Solution

  • You can accomplish this as follows:

    <img src="http://via.placeholder.com/350x150/222222" (click)="hiddenImage.style.display='inline'"/>
    <img #hiddenImage style="display: none" src="http://via.placeholder.com/350x150/888888"/>
    

    But it may still be a better idea to do it differently depending on what your exact use case is.

    Using *ngIf you would probably still need a variable that holds the value of whether the image should be shown or not in your template:

    <img src="http://via.placeholder.com/350x150/222222" (click)="showImage=true"/>
    <img src="http://via.placeholder.com/350x150/888888" *ngIf="showImage"/>
    

    In your Component you should declare:

    showImage: boolean = false;