如何在 Angular 库中包含图像? [英] How to include images in an Angular library?

查看:34
本文介绍了如何在 Angular 库中包含图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的 Angular 库,并且我希望我的库也显示图像.问题是,如果我将图像包含在库的模块文件夹中,然后从模块内部引用它,则会出现 404 错误.据我所知,在 Angular 项目中,图像必须放在/assets 文件夹中,但我确实需要将此图像包含在我的库中.

I created a simple Angular library and I want my library to also display an image. The problem is that if I include the image inside the module folder of my library and then refer to it from inside the module, I get 404 error. As far as I know, in an Angular project images must be placed inside /assets folder, but I really need to include this image in my library.

我将图像放在模块文件夹中,并从我的模块组件的 .html 文件中引用它:<img src="myImage.png">,但它不起作用.

I placed the image inside the module folder and refered to it from a the .html file of my module component:<img src="myImage.png">, but it doesn't work.

推荐答案

这里有几个选项,没有一个是完美的.

There are several options here, none of which is perfect.

图像可以使用 base64 编码为数据 URL 并用于内联模板:

An image can be encoded with base64 to data URLs and used in a template inline:

<img src="data:image/jpg;base64,...">

或者绑定到包含数据 URL 的组件属性:

Or be bound to component property that contains data URL:

<img [src]="imageFoo">

图像可以与包一起包含,并且可以指示用户将它们复制到网站公共目录中.由于公共路径事先未知,因此模块可以接受具有常规 forRoot 方法并将其用于图像路径:

Images can be included alongside with the package, and a user can be instructed to copy them into website public directory. Since public path is unknown beforehand, the module can accept image path configuration with conventional forRoot method and use it for image path:

@Component({
  ...
  template: `<img src="{{imagesPath}}/foo.jpg">`
})
class SomeComponent {
  constructor(@Inject(IMAGES_PATH) public imagesPath: string) {}
}

这篇关于如何在 Angular 库中包含图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆