我正在尝试将我的一个图像的相对路径放在我的资产文件夹中我的 Angular2 应用程序的图像 src 标记中。我在我的组件中将一个变量设置为“fullImagePath”并在我的模板中使用它。我尝试了许多不同的可能路径,但似乎无法提升我的形象。 Angular2 中是否有一些特殊路径总是相对于 Django 中的静态文件夹?
零件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
fullImagePath: string;
constructor() {
this.fullImagePath = '../../assets/images/therealdealportfoliohero.jpg'
}
ngOnInit() {
}
}
我还将图片与该组件放在同一个文件夹中,因此由于同一文件夹中的模板和 css 可以正常工作,因此我不确定为什么图像的类似相对路径不起作用。这是与同一文件夹中的图像相同的组件。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
fullImagePath: string;
constructor() {
this.fullImagePath = './therealdealportfoliohero.jpg'
}
ngOnInit() {
}
}
html
<div class="row">
<div class="col-xs-12">
<img [src]="fullImagePath">
</div>
</div>
应用树 \* 我省略了节点模块文件夹以节省空间
├── README.md
├── angular-cli.json
├── e2e
│ ├── app.e2e-spec.ts
│ ├── app.po.ts
│ └── tsconfig.json
├── karma.conf.js
├── package.json
├── protractor.conf.js
├── src
│ ├── app
│ │ ├── app.component.css
│ │ ├── app.component.html
│ │ ├── app.component.spec.ts
│ │ ├── app.component.ts
│ │ ├── app.module.ts
│ │ ├── hero
│ │ │ ├── hero.component.css
│ │ │ ├── hero.component.html
│ │ │ ├── hero.component.spec.ts
│ │ │ ├── hero.component.ts
│ │ │ └── portheropng.png
│ │ ├── index.ts
│ │ └── shared
│ │ └── index.ts
│ ├── assets
│ │ └── images
│ │ └── therealdealportfoliohero.jpg
│ ├── environments
│ │ ├── environment.dev.ts
│ │ ├── environment.prod.ts
│ │ └── environment.ts
│ ├── favicon.ico
│ ├── index.html
│ ├── main.ts
│ ├── polyfills.ts
│ ├── styles.css
│ ├── test.ts
│ ├── tsconfig.json
│ └── typings.d.ts
└── tslint.json
原文由 TJB 发布,翻译遵循 CC BY-SA 4.0 许可协议
Angular 仅指向
src/assets
文件夹,没有其他内容可以通过 url 公开访问,因此您应该使用完整路径或者
这仅在基本 href 标签设置为
/
您还可以在
angular/cli
中添加其他数据文件夹。您只需要修改angular-cli.json
编辑中的注意事项:Dist 命令将尝试从资产中查找所有附件,因此将要通过 url 访问的图像和任何文件保留在资产中也很重要,例如模拟 json 数据文件也应该在资产中。