首页 > 解决方案 > 如何从对象 url 以角度 ngFor 显示图像?

问题描述

for (let i = 0; i < newsValues.length; i++) {
  this.newsX[newsValues[i]] = {
    title: newsValues[i].title,
    date: newsValues[i].published_on,
    url: newsValues[i].url,
    body: newsValues[i].body,
    image: newsValues[i].imageurl,
    tags: newsValues[i].tags
  };
}    

在这里我得到了响应,我用我需要的属性制作了自己的对象,当我通过它时,除了图像之外,一切正常*ngFor

这是我的 HTML 部分:

<nz-layout>
    <nz-content>
      <header>
        <h1>Cool Articles</h1>
      </header>
      <div class="band">
        <div class="item-7" *ngFor="let news of newsData">
          <a href="{{news.url}}" class="card">
            <div class="thumb" [style.background-image]="'url('+news.image+')'">
            </div>
            <article>
              <h1>{{news.title}}</h1>
              <span>Release Date: {{news.date | date: 'yyyy-MM-dd'}}</span>
            </article>
          </a>
        </div>
      </div>
   </nz-content>
</nz-layout>

标签: angular

解决方案


  • 检查“news.image”值是否具有 http/https 协议。如果不是,您可能必须将其添加到原始数组或模板中。

    image: newsValues[i].imageurl, //Check for http/https 
    
  • 确保 'thumb' 类具有附加的高度和宽度属性。

Stackblitz - https://stackblitz.com/edit/angular-ewpahe?file=src/app/app.component.ts


推荐阅读