Manisha
Manisha

Reputation: 195

How to display image if path is in json

I am new in Angular and I am using Angular 8 I have list of path of images in 'dataSource' variable in JSON format like this:

hotdeals: Array(4) 
    0: {uri: "/Home/HotDeals/hotdeal1.png", id: "2"}
    1: {uri: "/Home/HotDeals/hotdeal2.png", id: "3"}
    2: {uri: "/Home/HotDeals/hotdeal3.png", id: "4"}
    3: {uri: "/Home/HotDeals/hotdeal4.png", id: "6"}

How can i show all this images on HTML if my base url is "http://localhost" and file path is above in JSON.
Note: Image path may increase or decrease. Means this time 4 image i got, but if i get 5 image path. So how can i handle this?

dashboard.component.html

ngOnInit() 
  {
    this.apiService.getHotDeals('pop').subscribe(home=>{
      this.dataSource=home;
console.log(this.dataSource)    

}

dashboard.component.html

<owl-carousel [options]="{items:3, dots:true, navigation:true}"
          [carouselClasses]="['owl-theme', 'row', 'sliding']" >          
                    <div class="best-deals-single"><a><img src="{{this.dataSource}}" height="300" width="200" alt=""></a></div>               
 </owl-carousel>

Screenshot of console of dataSource enter image description here

Upvotes: 1

Views: 1425

Answers (1)

Chris
Chris

Reputation: 2397

You must use a loop to display all images:

component:

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class YourComponentComponent {
  imgHost = environment.imgHost;
}

template:

<owl-carousel
  *ngIf="dataSource.hotdeals"
  [options]="{items:3, dots:true, navigation:true}"
  [carouselClasses]="['owl-theme', 'row', 'sliding']"
  [items]="dataSource.hotdeals" 
>
  <div class="item" *ngFor="let img of dataSource.hotdeals">
    <div style="align-content: center;">
      <img style="height: 260px; width: 100%;" [src]="imgHost + img.uri" />
    </div>
  </div>
</owl-carousel>

environment.json

export const environment = {
  imgHost: 'https://example.com'
};

and if your images are on the same server as the application

environment.prod.json

export const environment = {
  imgHost: ''
};

Upvotes: 3

Related Questions