Abhijit Chakra
Abhijit Chakra

Reputation: 3236

Angular change image based on dynamical value

Here is my below code

I am doing only if then else condition i want to do if else if if condition based on three value i want to change the image

<img [src]="status.getRequestStatus() == 'granted' ? 'assets/imgs/trafficlight_green.png':'assets/imgs/trafficlight_red.png' " class="image--background" >

this is for if and else condition i want to add if else if if

like if(new){someimage}else if(new1){some image1} if(new2){some image2}

Upvotes: 1

Views: 3587

Answers (4)

dev-dan
dev-dan

Reputation: 6283

You can keep the ternary statement in the template if you wanted to with the if else flow, as a ternary can be chained. It could look like so.

<img [src]="'new' ? 'green.png': new1 ? 'red.png' : 'amber.png'" class="image-background">

This would read like

if (new)
{ 'green.png' }

else if (new1)
{ 'red.png' }

else 
{ 'amber.png' } // being new2

Hope this is what you are looking for.

Upvotes: 1

Harun Or Rashid
Harun Or Rashid

Reputation: 5927

You can use multiple img tag on condition as below -

<img *ngIf="new" [src]="assets/imgs/trafficlight_green1.png" class="image--background">
<img *ngIf="new1" [src]="assets/imgs/trafficlight_green2.png" class="image--background">
<img *ngIf="new2" [src]="assets/imgs/trafficlight_green3.png" class="image--background">

Or use a variable to store image source in your component.ts and then bind it in component.html as below -

<img [src]="imageSource" class="image--background">

Upvotes: 1

Sunil Kashyap
Sunil Kashyap

Reputation: 2984

Move logic to component.

In your component.html

<img [src]="someFn()" class="image--background" >

In your component.ts

someFn() {
    let rtn = '';
    if(...) {
        rtn = ...
    } else if (...) {
       ...
    } else {
       ...
    }
    return rtn;
}

Upvotes: 2

rmjoia
rmjoia

Reputation: 980

try this solution based on my comment:

Check the example on StackBlitz

The validation is made on the component, on your getRequestStatus() I used ngOnInit with a timeout to change "dynamically"

the source is automatically updated based on the source property change.

view:

<img [(src)]="sourceImage" width="200" />

component:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name = 'Angular';
  sourceImage: string;

  ngOnInit() {
    this.sourceImage = 'https://angular.io/assets/images/logos/angular/angular.svg';

    setTimeout(()=> {
        this.sourceImage = 'https://dwglogo.com/wp-content/uploads/2017/03/AngularJS_logo_004.svg';
    }, 2000)
  }
}

Upvotes: 0

Related Questions