我正在尝试将我的 Assets 文件夹中的一张图像的相对路径放在我的 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>
app tree * 我省略了节点模块文件夹以节省空间
├── 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
最佳答案
Angular 仅指向 src/assets
文件夹,没有其他内容可以通过 url 访问,因此您应该使用完整路径
this.fullImagePath = '/assets/images/therealdealportfoliohero.jpg'
或者
this.fullImagePath = 'assets/images/therealdealportfoliohero.jpg'
这仅在基本 href 标签设置为 /
时有效
您还可以在 angular/cli
中为数据添加其他文件夹。
您只需要修改 angular-cli.json
"assets": [
"assets",
"img",
"favicon.ico",
".htaccess"
]
编辑中注意: Dist 命令将尝试从 Assets 中查找所有附件,因此将图像和您想要通过 url 访问的任何文件保存在 Assets 中也很重要,例如模拟 json 数据文件也应该在 Assets 中。
关于html - 如何在 Angular2 中提供图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40230473/