首页 > 解决方案 > 基于连续扩展的 Angular 2/4 显示图像

问题描述

嗨,我有以下代码来显示图像。

<div  *ngFor="let image of images" >
   <span *ngIf="    ">  //if img=t.jpg display this line
  <label>JPEG Image</label><img src='{{image.img}}'/>
   </span>
      <span *ngIf="    "> // if img=t.jpg dont display this line
  <label>PNG Image</label><img src='{{image.img}}'/>
   </span>
</div>

我想提出条件,如果图像扩展名是 .jpg 即 image.jpg 我要显示 JPEG 行,如果是 .png 即 image.png 我要显示 PNG 图像行。请让我知道如何在 *ngIf 中读取图像/文件的扩展名 谢谢

标签: javascripthtmlangular

解决方案


这是示例代码,请检查

StackBitz 网址

零件

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
   images = [
    {
      img: 'https://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg',
    },
    {
      img: 'https://vignette.wikia.nocookie.net/fantendo/images/6/6e/Small-mario.png',
    }
  ];
  public getExstendsion(image) {
    if (image.endsWith('jpg') || image.endsWith('jpeg')) {
      return 'jpg';
    }
    if (image.endsWith('png')) {
      return 'png';
    }
  }
}

html

 <div  *ngFor="let image of images" >
  
   <span *ngIf="(getExstendsion(image.img) == 'jpg') || getExstendsion(image.img) == 'jpeg'"> 
  <label>JPEG Image</label><img src='{{image.img}}'/>
   </span>
      <span *ngIf="getExstendsion(image.img) == 'png'"> 
  <label>PNG Image</label><img src='{{image.img}}'/>
   </span>
</div>

推荐阅读