mardi 15 septembre 2020

Use an image asset in an Angular Library Component Template

I'm using Angular 10 and I want to create a component library that will have some images and stylesheets. I need to be able to reference those images from within component templates defined in the component html template.

This seems like it should be a pretty easy thing to do, right?

I'm pretty new to Angular, but I'm a veteran software engineer and I want to make sure we can get Angular to work within our CI environment (Jenkins). This means builds are portable (don't require hard-coded paths or parameters), automatically buildable, testable, and deployable.

I've seen this link: Angular component library - image references in templates

It doesn't appear to propose a workable solution for what I want to do.

I'm able to build, run tests, and publish our library packages to our internal npm repository.

With Angular 9+, assets get copied to the dist folder just fine, so that's not an issue.

What I can't figure out is how to reference the images from the library component's html templates. Everything I've tried results in a 404. All of the proposed solutions I've seen don't work. A number of solutions propose putting the images in encoded strings in the templates. I'd really like to avoid that, if possible, as it adds extra steps to getting assets into libraries.

I want to be able to reference the images both when testing the application in a workspace, and after the library is in an npm package. That way, it will work both when I'm building and testing in CI, and after the npm package is imported into a project.

Seems like this should be easier. Maybe I'm missing something obvious.

I put the images in the library under src/assets/images.

Now, I want to use an image in, let's say, an 'img' element in one of the library's html templates.

Links I've tried (most of these I got from proposed solutions):

  • '/assets/images/myimg.png'
  • '../assets/images/myimg.png'
  • 'assets/images/myimg.png'
  • '/src/assets/images/myimg.png'

etc.

I think I tried just about every variation possible, with no luck.

Is there some configuration I need to do to get it to work? Where does the assets folder end up relative to the library?

Aucun commentaire:

Enregistrer un commentaire