Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of filenames in assets folder with Typescript

How do I get all filenames in a folder using Typescript? It's for an angular 2 project.

To be more specific, what I'm trying to do is set the images for a bootstrap carousel using images from my photos folder. Currently I'm doing this:

private _images: Image[] = []

ngOnInit(): void {
    this._images = [
        { "title": "Slide 1", "url": "../photos/carousel/gg_slide 1.jpg" },
        { "title": "Slide 2", "url": "../photos/carousel/gg_slide 2.jpg" },
        { "title": "Slide 3", "url": "../photos/carousel/gg_slide 3.jpg" },
        { "title": "Slide 4", "url": "../photos/carousel/gg_slide 4.jpg" },
        { "title": "Slide 5", "url": "../photos/carousel/gg_slide 5.jpg" }
    ]
}//ngOnInit 

Then using the the images array in the html file like this:

<carousel>
    <slide *ngFor="let img of _images">
        <img src="{{img.url}}" alt="{{img.title}}">
    </slide>
</carousel>

I'd like to be able to just loop through whatever files are in the photos folder and add them to the images array. That way all I have to do to update the carousel is to change the photos in the photos folder.

like image 916
ShanieMoonlight Avatar asked Jul 20 '17 17:07

ShanieMoonlight


1 Answers

I have been unable to find a solution using Javascript. It appears that JS does not have the ability to read file structures. Instead you will have to keep a list on the backend in a database or create a json file that you keep up to date with all of the icons manually.

I have found this example.

As accessing file from assets folder is easy, so we can exploit it
and we can store an array of icon file names in the file say, icons.json.

1. Create icons.json as following in the assets folder-

{  // ---------- icons.json---------
  "icons-array" : ["icon-name1", "icon-name2", "icon-name3"]
}

2. Keep icon-name1.svg, icon-name2.svg, icon-name3.svg file in the assets/icons folder.
3. Read icons-json file at start-up of the angular application.
     How to read file at Angular Application Start-up

4.  After reading icons.json content, store value of icons-array property into a global accessible array, say     globalAccessibleIconsArray.
5.  And use the array as-

for (const icon of globalAccessibleIconsArray) {
      this.matIconRegistry.addSvgIconInNamespace(
        'my-namespace',
        icon,
        domSanitizer.bypassSecurityTrustResourceUrl(`./assets/icons/${icon}.svg`)
      );
    }


So, for Adding a new icon

  • you have to put the new icon file in the assets/icon folder, and
  • add the new file name in the icons.json file present in the assets folder.
like image 58
Jeremy Avatar answered Nov 12 '22 16:11

Jeremy