2017-04-06 40 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>