猿问

动态绑定图像 Angular 8

我object array需要根据信用卡类型动态添加图像图标,


.ts 文件


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

      }

    })

    );

  }

在 HTML 模板上,我尝试根据信用卡类型动态绑定图像,这就是我尝试过的,


html文件


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

问题是我只有相同的图标,即使是万事达卡或美国运通卡,我想在 stackblitz 上重现,但它不支持静态图像,有人知道如何解决这个问题或任何建议吗?


白衣非少年
浏览 189回答 1
1回答

烙印99

只有一个icon变量,每次forEach()迭代时都会重新分配一个新的图标路径。这一张icon用于所有卡片,因此只显示一张图像。方法一:你可以有一个像这样的图标对象var icons = {&nbsp;'Mastercard': '../../assets/svg/logo-mastercard.svg',&nbsp;'Amex': '../../assets/svg/icon-amex.svg'};&nbsp;而在 HTML 中,只需根据卡片类型使用适当的图标即可。<div class="flex-float">&nbsp; <div class="float-end">&nbsp; &nbsp; <img class="select--icon" [src]="icons[selectedCard.cardType]" />&nbsp; &nbsp; &nbsp; <p class="selected--desc is-hidden-mobile-xs">&nbsp; &nbsp; &nbsp; &nbsp; {{ selectedCard.cardType }}&nbsp; &nbsp; &nbsp; </p>&nbsp; </div></div>无需对saveCreditCard数组中的任何更改ngOnInit()。方法二:如果要在 中的每个对象上存储图标saveCreditCard,则可以使用Array.map()。在 中ngOnInit(),为每张信用卡分配图标。ngOnInit() {&nbsp; this.savedCreditCard = this.savedCreditCard.map(card => {&nbsp; &nbsp; let icon;&nbsp; &nbsp; if (card.cardType === 'Mastercard') {&nbsp; &nbsp; &nbsp; icon = '../../assets/svg/logo-mastercard.svg';&nbsp; &nbsp; } else if (card.cardType === 'Amex') {&nbsp; &nbsp; &nbsp; icon = '../../assets/svg/icon-amex.svg';&nbsp; &nbsp; }&nbsp; &nbsp; return {...card, "icon": icon};&nbsp; });&nbsp;}然后在 HTML 中,使用卡片的icon属性。<div class="flex-float">&nbsp; <div class="float-end">&nbsp; &nbsp; <img class="select--icon" [src]="selectedCard.icon" />&nbsp; &nbsp; &nbsp; <p class="selected--desc is-hidden-mobile-xs">&nbsp; &nbsp; &nbsp; &nbsp; {{ selectedCard.cardType }}&nbsp; &nbsp; &nbsp; </p>&nbsp; </div></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答