简体   繁体   English

如何在angular2中加载图像

[英]How to load images in angular2

Hello I am new to angular 2 . 您好,我是Angle 2的新手。 I am in a small project , where I have to set images. 我在一个小项目中,必须在其中设置图像。 This is my app.component.ts 这是我的app.component.ts

` `

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() {
  }
}

` `

and the html is ` 而html是`

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

` `

but in this process I have to declare all the images in separate variable.but I want to declare an array ,and load all and use them like ` 但是在这个过程中,我必须在单独的变量中声明所有图像。但是我想声明一个数组,然后全部加载并像`

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

` `

You can use *ngFor if you want to iterate through an array. 如果要遍历数组,可以使用*ngFor For example, if you have this array of image paths: 例如,如果您具有以下图像路径数组:

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

You can do this in your html: 您可以在html中执行此操作:

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

If you want to only iterate through an array of image names you can do it this way: 如果只想遍历图像名称数组,则可以采用以下方式:

If you get an array with image names while already having a base URL: 如果在已经具有基本URL的情况下获得具有图像名称的数组:

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

You can do it this way: 您可以这样操作:

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

Or, if you haven't set an imageUrl property, you can do this: 或者,如果您尚未设置imageUrl属性,则可以执行以下操作:

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

Yes I got it 是,我懂了

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

and I don't have to declare as an array. 而且我不必声明为数组。 just 只是

this.fullImagePath = '/assets/imges';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM