2017-04-06 51 views
0

你好,我是新的角2。我在一個小型項目中,我必須設置圖像。 這是我app.component.ts如何在angular2中加載圖像

`

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/imges/therealdealportfoliohero.jpg' 
    } 
ngOnInit() { 
    } 
} 

`

和HTML是 `

<div class="row"> 
    <div class="col-xs-12"> 
     <img [src]="fullImagePath"> 
    </div> 
</div> 

`

,但在這個過程中我有將所有圖像聲明爲單獨的變量,但我想要de克萊爾一個數組,並加載所有,並利用它們像`

<div class="row"> 
    <div class="col-xs-12"> 
     <img [src]="fullImagePath/(myImagename)"> 
    </div> 
</div> 

`

回答

0

是的我知道了

<img id="logo" [src]="fullImagePath + '/logo.png'" alt="Simpla Admin logo" />

我不必聲明爲一個數組。 只是

this.fullImagePath = '/assets/imges';

2

您可以使用*ngFor,如果你想通過數組進行迭代。 例如,如果你有這樣的陣列成像路徑:

this.imagePaths = ['image/path/1.png', 'image/path/2.png', 'image/path/3.png'] 

在你的HTML你可以這樣做:

<div class="row"> 
    <div class="col-xs-12"> 
     <div *ngFor="let path of imagePaths"> 
      <img [src]="path"> 
     </div> 
    </div> 
</div> 

如果你想僅僅通過圖片的名字,你可以做的迭代一個數組它是這樣的:

如果你得到的圖像名稱的數組,而已經有一個基本的URL:

this.imageUrl = '/assets/images/'; 
this.images = ['1.png', '2.png', '3.png']; 

你可以這樣來做:

<div class="row"> 
    <div class="col-xs-12"> 
     <div *ngFor="let image of images"> 
      <img src="{{imageUrl + image}}"> 
     </div> 
    </div> 
</div> 

或者,如果您沒有設置一個imageUrl屬性,你可以這樣做:

<div class="row"> 
     <div class="col-xs-12"> 
      <div *ngFor="let image of images"> 
       <img src="/assets/images/{{image}}"> 
      </div> 
     </div> 
    </div> 
+0

你做得很好,我很欣賞它。但是我想作這樣的事' this.path =」 /資產/ IMGS。; ' –

+0

我編輯它提供了一種不同的方法 – DGarvanski

+0

哇,這是一個很棒的方法:) –

-2
u can try like this: 


images= ['baseImagePath/image1', 'baseImagePath/image2', 'baseImagePath/image3']; 
在HTML

<li *ngFor="let image of images"> 
     <img [src]="image"> 
     </li>