Angular2 アプリの画像 src タグに、assets フォルダー内の画像の 1 つへの相対パスを配置しようとしています。コンポーネント内の変数を '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
ベストアンサー1
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 コマンドはアセットからすべての添付ファイルを検索しようとするため、URL 経由でアクセスする画像やファイルをアセット内に保持することも重要です。たとえば、モック JSON データ ファイルもアセット内に保持する必要があります。