Creating a dynamic image binding feature in Angular 8

I am working with an object array that requires me to dynamically add an image icon based on the type of credit card.

Typescript file

  icon: any;

  savedCreditCard = 
  [
  {
    cardExpiryDateFormat: "05/xx",
    cardNumberLast: "00xx",
    cardId: "xxx",
    cardType: "Mastercard",
    cardExpiryDate: "xx05",
    paymentChannelId: 9,
    cardNumberMasked: "512345XXXXXXXXXX"
  },
  {
    cardExpiryDateFormat: "11/xx",
    cardNumberLast: "58xx",
    cardId: "xxx",
    cardType: "Amex",
    cardExpiryDate: "xx11",
    paymentChannelId: 16,
    cardNumberMasked: "379185XXXXXXXXX"
  }
]

  ngOnInit() {
        this.savedCreditCard.forEach((x => {
      if (x.cardType === 'Mastercard') {
        this.icon = '../../assets/svg/logo-mastercard.svg';
      } else if (x.cardType === 'Amex') {
        this.icon = '../../assets/svg/icon-amex.svg';
      }
    })
    );
  }

When binding the image dynamically in the HTML template based on the type of credit card, I encountered an issue where I only get the same icon regardless of whether it is a Mastercard or Amex. Here is what I have tried:

HTML file

    <div class="flex-float">
      <div class="float-end">
        <img class="select--icon" [src]="icon" />
        <p class="selected--desc is-hidden-mobile-xs">
          {{ selectedCard.cardType }}
        </p>
      </div>
    </div>

I attempted to reproduce the issue on StackBlitz but it does not support static images. Does anyone have any suggestions on how to solve this problem?

Answer №1

During each iteration of the forEach() loop, the icon variable is reassigned with a new icon path. This results in only one image being displayed because the same icon is used for all cards.

Solution 1:

An alternative approach is to create an object containing icons for each card type:

var icons = {
 'Mastercard': '../../assets/svg/logo-mastercard.svg',
 'Amex': '../../assets/svg/icon-amex.svg'
}; 

In your HTML code, display the appropriate icon based on the selected card type.

<div class="flex-float">
  <div class="float-end">
    <img class="select--icon" [src]="icons[selectedCard.cardType]" />
      <p class="selected--desc is-hidden-mobile-xs">
        {{ selectedCard.cardType }}
      </p>
  </div>
</div>

No modifications are needed in the ngOnInit() method for the saveCreditCard array.

Solution 2:

If you prefer to store the icon with each credit card object in the saveCreditCard array, you can use Array.map().

Within the ngOnInit() method, assign an icon to each credit card object.

ngOnInit() {
  this.saveCreditCard = this.saveCreditCard.map(card => {
    let icon;
    if (card.cardType === 'Mastercard') {
      icon = '../../assets/svg/logo-mastercard.svg';
    } else if (card.cardType === 'Amex') {
      icon = '../../assets/svg/icon-amex.svg';
    }

    return {...card, "icon": icon};
  }); 
}

In your HTML code, access the icon property of the selected card.

<div class="flex-float">
  <div class="float-end">
    <img class="select--icon" [src]="selectedCard.icon" />
      <p class="selected--desc is-hidden-mobile-xs">
        {{ selectedCard.cardType }}
      </p>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular: Displaying data in a list format from a multidimensional array

My data structure is as follows: { 'TeamLeader': 'Andrew', 'subordinates': [{ 'Name': 'Daniel', 'subordinates': [{ 'Name': 'Stev ...

Troubleshooting the issue of browser prefix injections not functioning properly in Vue when using the

I've spent an entire afternoon on this issue and I'm completely stuck. After realizing that IE11 doesn't support grid-template, I learned that I need to use -ms-grid-columns and -ms-grid-rows instead. I am attempting to generate CSS and inje ...

Guide to properly deserializing a JSON string into a class with a nested List of different class members

I have a scenario where I am sending a JSON stringified "View" object from the browser to an ASP.Net Page Method using Jquery's $.Ajax(). The issue I am facing is that while the Javascript deserialization is successful for all the strings and integers ...

Ways to prevent the repetition of keys associated with values

I am currently dealing with an array called serialNumbers, which can have different structures. For example: lot: 1 Serial: 2 lot: 1 Serial: 3 lot: 1 Serial: 4 ...or it could look like this: lot: 1 Serial: 5 lot: 1 Serial: 9 lot: 8 Serial: 2 lot: ...

Problem with rendering React Router v4 ConnectedRouter on nested routes

The routes for the first level are correctly displayed from Layout.tsx, but when clicked on ResourcesUI.tsx, the content is not rendered as expected (see code below). The ResourceUI component consists of 2 sections. The left section contains links, and th ...

Leveraging Ajax with PlayFramework Results

As stated in the PlayFramework Document 2.0 and PlayFramework Document 2.1, it is known that Play can return various responses such as: Ok() badRequest() created() status() forbidden() internalServerError() TODO However, when trying to send a response wi ...

utilizing ng-option to present choices in a dropdown menu

I have been implementing a scroll-down menu in my application using options. However, I now want to switch to using ng-option to populate the values from a JavaScript file. I also require assistance with writing AngularJS code for this task. Below is a s ...

I am looking to update my table once I have closed the modal in Angular

I am facing an issue with refreshing the table in my component using the following function: this._empresaService.getAllEnterprisePaginated(1);. This function is located in my service, specifically in the modal service of the enterprise component. CODE fo ...

I am having an issue with my jQuery form submission not sending any POST variables

My code seems to be having issues as the PHP file is not receiving the POST-variables. I am unsure of what could be going wrong, so I am reaching out for some guidance. Here is the HTML: <div id="preloader" class="preload"></div> <div id=" ...

Is JSON Compatible with the Switch Statement?

Could someone help me with creating a switch statement in JSON? {"Errors":{"key1":"afkafk"},"IsValid":false,"SuccessMessage":""} I attempted to use: switch(response) { case response.Errors.key1: alert('test'); default: } However, t ...

"Utilizing an exported constant from a TypeScript file in a JavaScript file: A step-by-step guide

I am facing an issue when trying to import a constant from a TypeScript file into a JavaScript file. I keep encountering the error Unexpected token, expected ,. This is how the constant looks in the ts file: export const articleQuery = (slug: string, cate ...

Unexpected behavior with if statements in jQuery

Having recently started using jQuery, I am embarking on the creation of a survey. Each question within the survey resides in its own div and is unveiled upon clicking the "Next" button. Currently, all divs are hidden except for the current one. My approach ...

Stopping an endless loop in JavaScript by pressing a key on the keyboard can be a useful

I've been working on creating a JavaScript game and am currently tackling the challenge of implementing gravity. One crucial aspect I need to address is creating an infinite loop without causing the browser to crash. Is there a way for me to include a ...

Issues with jagged borders in three.js while working with gltf documents

Seeking assistance for resolving an issue with a bug. https://i.sstatic.net/F1fov.png The problem is seen in the gltf import of a "sheep-like" object, exported by blockbench. Adjusting the scale does not solve the bugged edges that persist no matter what ...

Tips for adjusting div content to fit a fixed height on all devices

Looking to adjust the size of the #left-content div based on the height of the window, while ensuring that all content is visible within the fixed #left-bg. However, when viewing on mobile or tablet devices, the content appears hidden. .left-bg{ backgro ...

Can you include conditional logic within a switch statement?

I've been using if, else if, and else statements in my code but recently switched to switch statements which have made things much simpler. Now I'm wondering if it's possible to add multiple conditions inside a switch statement, similar to i ...

Insert a new row below an existing row within a Material table

Is it possible to dynamically insert a new row under a specific existing row in a table within the DOM without having to redefine all of the data in the MatTableDataSource? ...

How can I create a universal "Add" button in Angular that can be used across all child components?

Currently, I am working on a straightforward application featuring a toolbar at the top of the screen. Within this toolbar, there is a + button designated for adding content. The functionality of this + button changes based on which component is currently ...

Performing a Javascript query to update the value in a spreadsheet with Selenium integration

How can I set a cell value using JavaScript in Selenium when the element has been created using spreadjs and I am unable to access the element's value? string query = "GcSpread.Sheets.findControl(document.getElementById(\"" + _sheetName + "&bsol ...

How to make views in React Native adjust their size dynamically in a scrollview with paging functionality

Has anyone successfully implemented a ScrollView in React Native with paging enabled to swipe through a series of images? I am having trouble making the image views fill each page of the scroll view without hardcoding width and height values for the image ...