根据文件扩展名设置图标。 Angular 7

set icon based on file extention. Angular 7

我正在使用 Angular 7,我有一个列表,其中显示了一些带有图标的文档名称。此时此刻,无论文档是什么,我都显示相同的图标,但我有 Excel 文档、pdf、文档、图像等的图标。我想知道是否有办法设置基于图标在文档扩展名上。

到目前为止我是这样的:

与 html 像这样:

<h6 class="list-tittle">
  Documentos
</h6>
<div >
  <ul class="list-group">
    <li *ngFor="let document of documents;" class="list-item"><i class="fa fa-file-pdf-o" style="color:#5cb85c;" aria-hidden="true"></i> {{document}}</li>
  </ul>
</div>
<button type="button" class="btn  tolowercase">Agregar Documento</button>
<h6 class="list-tittle">
  Anexos
</h6>
<div>
  <ul class="list-group">
    <li *ngFor="let anexo of anexos;" class="list-item"><i class="fa fa-file-excel-o" style="color:#5cb85c;" aria-hidden="true"></i> {{anexo}}</li>
  </ul>
</div>
<button type="button" class="btn  tolowercase">Agregar Anexo</button>

预期的行为是列表显示如下图标: 预期的:

感谢任何帮助。

为此你必须做以下事情

1) 提取每个文档的扩展名

2) 创建一个包含图标 class 名称的数组,每种类型

使用下面的例子

.ts

export class AppComponent {
  documentList = ["document1.pdf", "document2.xlsx", "document3.jpg"];
  iconList = [ // array of icon class list based on type
    { type: "xlsx", icon: "fa fa-file-excel-o" },
    { type: "pdf", icon: "fa fa-file-pdf-o" },
    { type: "jpg", icon: "fa fa-file-image-o" }
  ];

  getFileExtension(filename) { // this will give you icon class name
    let ext = filename.split(".").pop();
    let obj = this.iconList.filter(row => {
      if (row.type === ext) {
        return true;
      }
    });
    if (obj.length > 0) {
      let icon = obj[0].icon;
      return icon;
    } else {
      return "";
    }
  }
}

.html

<div *ngFor="let filename of documentList"> 
      <i class="{{getFileExtension(filename)}}" style="color:#5cb85c;" aria-hidden="true"></i> 
      {{filename}}
</div>

工作示例link

https://stackblitz.com/edit/angular-4bexr3?embed=1&file=src/app/app.component.html