【问题标题】:how to connect images in angular using json如何使用json以角度连接图像
【发布时间】:2020-03-14 03:36:50
【问题描述】:

我有以下结构,其中有 json 格式的图像数据,其中包含指向 assets 文件夹的链接。放置所有图像的位置。我正在考虑使用这种使用图像的方式进行测试,因为将来我们将在网络的某个地方拥有图像,并将根据类似的 JSON 从那里获取:

- app
   - core
   - data 
       - img.json
   - layout
       - test.component.ts
- assets
   - images

img.json

{
  "items" : [
    {
      "img": "/assets/images/test1.png",
      "alt" : "Image 1"
    },
    {
      "img": "/assets/images/test2.png",
      "alt" : "Image 2"
    },
    {
      "img": "/assets/images/test3.png",
      "alt" : "Image 3"
    }
  ]
}

test.component.ts

import images from '../../data/img.json';

export class SlideshowComponent implements OnInit {
  showNavigationArrows = false;
  showNavigationIndicators = false;
  items = [0, 1, 2].map((n) => images);

  constructor(config: NgbCarouselConfig) {
    // customize default values of carousels used by this component tree
    config.showNavigationArrows = true;
    config.showNavigationIndicators = true;
  }    
}

HTML

<ngb-carousel *ngIf="items" [showNavigationArrows]="showNavigationArrows" 
[showNavigationIndicators]="showNavigationIndicators">
  <ng-template ngbSlide *ngFor="let item of items">
    <div class="picsum-img-wrapper">
      <img [src]="item" alt="Random slide">
    </div>
  </ng-template>
</ngb-carousel>

我无法将图像连接到 HTML,任何帮助都会很棒。

【问题讨论】:

    标签: html json angular typescript


    【解决方案1】:

    假设您的 tsconfig 已正确配置为导入 json(如果没有,您的 ts 编译器会向您抛出错误)

    你应该能够做到这一点:

    items = images.items; // not sure why you had that index -> map structure?
    

    <ng-template ngbSlide *ngFor="let item of items">
      <div class="picsum-img-wrapper">
        <img [src]="item.img" alt="{{ item.alt }}"> <!-- access the url and use the alt text -->
      </div>
    </ng-template>
    

    基于 cmets 的额外内容:

    如果您想选择性地显示视频标签,我建议您这样做:

    items = images.items.map(i => Object.assign({}, i, {isVideo: i.img.endsWith('.mov')})) // this only works for mov obviously
    

    模板:

    <ng-template ngbSlide *ngFor="let item of items">
      <div class="picsum-img-wrapper">
        <img *ngIf="!item.isVideo" [src]="item.img" alt="{{ item.alt }}"> <!-- simple ngIf to show right tag -->
        <video *ngIf="item.isVideo" [src]="item.img" alt="{{ item.alt }}" controls></video>
      </div> 
    </ng-template>
    

    【讨论】:

    • 太棒了——它奏效了。我完全错过了删除地图结构 - 但无论如何我仍然错过了 images.items - 如果同一文件夹中有movie.mov文件。有没有办法让它运行。
    • 在这种情况下你需要一个视频标签吗?解析出扩展并使用基于它的 ngIf 或 switch 语句
    • 你能帮忙吗,因为这是我第一次在 Angular latest 上尝试这样的事情
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2019-06-06
    • 2019-06-19
    • 2022-01-26
    • 2021-11-05
    • 2019-03-09
    • 2020-09-11
    相关资源
    最近更新 更多