Home > Software design >  Change img [src] specifically with ngSwitch
Change img [src] specifically with ngSwitch

Time:11-28

I want to change img tag src based on a condition. I am using ternary operator right now; I want to ask is there a way to use ngSwitch instead (WITHOUT REPEATING the img tag). Here is my code:

<div>
  <img height='26' width='22' [src]="
       bank.bankName.includes('a') ? 'assets/images/a.png' :
       bank.bankName.includes('b') ? 'assets/images/b.png' :
       bank.bankName.includes('c') ? 'assets/images/c.png' :
       bank.bankName.includes('d') ? 'assets/images/d.png' : ''
  " />
</div> 

CodePudding user response:

Writing code in a chain of ternary operators is never really a good move, especially in HTML templates. The switch is fine and if you really want to avoid it, you can simply write this code in component.ts file and set an public imageSrc = '' named peropty, compute the result and assign it.

<div>
  <img height='26' width='22' [src]="imageSrc" />
</div> 

CodePudding user response:

I would create a pipe, , so you write the code only once and then just add it to the html, , especially if you are going to use it in more components, and it will be easy to change in the future.

Just something like this: For using:

<img height='26' width='22' [src]="bank.bankName | bankNameImagePipe" />

Pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'bankNameImagePipe',
})
export class BankNameImagePipe implements PipeTransform {

  transform(value: string): string {

    let urlBankImg: string = 'assets/images/';

    switch (value) {
      case value.includes('a'):
        urlBankImg = 'a.png';
        break;
      case value.includes('b'):
        urlBankImg = 'b.png';
        break;
      case value.includes('c'):
        urlBankImg = 'c.png';
        break;
      case value.includes('d'):
        urlBanckImg = 'd.png';
        break;

      default:
        urlBankImg= ''; // You can add a 'default' image url here
        break;
    }

    return urlBankImg;
  }
}

NOTE: I assume that bank.bankName will be a string and not an array. If it were not a string, you would have to change the pipe appropriately.

  • Related