Issue
I'm working with Angular 7, and I have a list where I display some document names with an icon. At this momento I'm displaying the same icon no mather what document is, but I have icons for Excel document, pdf, doc, image, etc. I want to know if is there a way to set the icon based on the document extention.
With html like this:
<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>
And the expected behaviour is that the list display the icons like this: EXPECTED:
I appreciate any help.
Solution
For this you have to do following things
1) Extract extension of each document
2) make an array containing icon class name with each type
use below example
.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>
Working example link
https://stackblitz.com/edit/angular-4bexr3?embed=1&file=src/app/app.component.html
Answered By - Passionate Coder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.