【问题标题】:angular 2 display array of images角度2显示图像数组
【发布时间】:2017-08-22 08:33:13
【问题描述】:

我是 angular 2 的新手,我有一个图像数组,我想连续显示所有图像,但即使数组不为空,也没有显示任何图像 我正在使用代码中显示的 img 标签

html代码:

<div fxLayout="column">


    <div >

    </div>

    <div fxLayout="row" *ngIf="doneLoadingProjectData" >
      <div  *ngFor="let image of images" >
          <img src='image'/>
      </div>

    </div>


</div>

【问题讨论】:

  • ngIf 和 ngFor 不能在同一个元素中使用。查看此解决方案以了解 ng-container 解决方法:stackoverflow.com/questions/34657821/…
  • 如果 [src] 不起作用,你必须Sanitize url。

标签: javascript angularjs arrays


【解决方案1】:

为src属性赋值时需要使用大括号

<div  *ngFor="let image of images" >
  <img src='{{image}}'/>
</div>

或者你可以使用模板表达式:

<img [src]="image" />

【讨论】:

    【解决方案2】:

    另外我认为图像数组需要是图像链接的数组(最好使用 JSON),然后当使用 ngFor 显示每个图像时,图像才会显示在浏览器上

    <div *ngIf="images">
    <ul>
      <li *ngFor="let image of images">
            <img [src]="image.href" />
      </li>
    </ul>
    

    另外我认为也许更好的是使用 ngOnInit 以便在调用该 div 时完成所有初始化

    <div ngOnInit>
    <ul>
      <li *ngFor="let image of images">
            <img [src]="image.href" />
      </li>
    </ul>
    

    并且在组件中你可以随心所欲地运行你的代码

     images = [];
     ngOnInit() { type your code here it is similar to a constructor, here you can call your service or factory to get array of images you can initialize images here }
    

    图像数组是这样的

    { “图片” : [ { “名称”:“图像1”, "href" : "http://east-nj1.photos.example.org/987/nj1-1234" }, { “名称”:“图像2”, "href" : "http://east-nj1.photos.example.org/987/nj1-1234" }, { “名称”:“图像3”, "href" : "http://east-nj1.photos.example.org/987/nj1-1234" }, { “名称”:“图像4”, "href" : "http://east-nj1.photos.example.org/987/nj1-1234" } ] }

    复制 将此块引用粘贴到此链接中,您将了解如何传递数据link 您可以访问 JSON 值的每个属性作为 image.name 和 image.href。希望你觉得这很有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-03
      • 2018-06-02
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多