A guide on showing an image from a JSON file path

As a beginner in Angular, I am currently working with Angular 8. I have a list of image paths stored in the 'dataSource' variable in JSON format, like so:

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"}

I am wondering how to display all these images on HTML, considering my base URL is "http://localhost" and the file paths are as mentioned in the JSON above.
Note: The number of image paths may vary. For example, if I receive 5 image paths, how can I handle that dynamically?

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>

Here's a screenshot of the console displaying the 'dataSource': https://i.sstatic.net/LTvb6.png

Answer №1

To display all images, it is necessary to utilize a loop:

Component Setup:

@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 Implementation:

<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 Configuration - environment.json:

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

If the images are hosted on the same server as the application:

Environment Configuration - environment.prod.json:

export const environment = {
  imgHost: ''
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing buttons from a table row dynamically

Below is how I am adding the Button to Element: (this.sample as any).element.addEventListener("mouseover", function (e) { if ((e.target as HTMLElement).classList.contains("e-rowcell")) { let ele: Element = e.target as Element; let ro ...

What are the steps to expand the express object with TypeScript?

I am facing an issue where, after compiling a typescript project, the express import import {Request, Response} is not showing up. I am now attempting to use require, but I am unsure of how to extend the express object and utilize req and res. Any assistan ...

Attempting to send numerous identifiers in an API request

I encountered a problem while working on a function in Angular that involves pulling data from an API. My goal is to enhance a current segment to accommodate multiple IDs, but I face difficulties when attempting to retrieve more than one ID for the API que ...

Achieving seamless integration among react-templates, TypeScript, and webpack

I am attempting to integrate TypeScript, react-templates, and webpack for a seamless workflow. My starting point was the sample code provided at https://www.typescriptlang.org/docs/handbook/react-&-webpack.html. The configuration in the webpack.config ...

Did the IBM MobileFirst client miss the call to handleFailure?

I am currently utilizing the IBM MFP Web SDK along with the provided code snippet to send challenges and manage responses from the IBM MobileFirst server. Everything functions properly when the server is up and running. However, I have encountered an iss ...

disappearing of vue event on single file component HTML element

I'm currently working on an ElectronJs project with Electron Forge, using the Webpack + Typescript template project In addition to that, I've integrated Vue and vue-loader for webpack in order to utilize Single File Component (SFC) files: { ...

Steps to perform a task that relies on two observables

I'm currently working on a function that requires two responses from two separate asynchronous functions, both returning observables. 1. Func1 returns an observable 2. Func2 returns an observable These functions are independent and can be executed sep ...

Display a specific section depending on the user's input by utilizing either ng-if or ng-show

I have a scenario where I need to display one of two sections based on user input. If the user selects 'Daily' in the first 'type' input, I want section 1 to appear (Enter start date and hour). For any other type selection, I want secti ...

When using the async pipe with Angular's ngFor, an error message indicates that the argument is

Can you explain why this error message is appearing: Argument of type '[string, { startTime: string; endTime: string; }][] | null' is not assignable to parameter of type 'Collection<unknown>'. It occurs when attempting to utilize ...

"Encountering issues with importing Splitpanes while using VueJs and TypeScript combination

My VueJS view was originally written in JavaScript using the component "splitpanes" from npm package. The code was functioning well with the following structure: <template> <div> <Splitpanes :dbl-click-splitter="false" :horizont ...

Creating types for React.ComponentType<P> in Material-UI using TypeScript

I am currently working with Typescript and incorporating Material-UI into my project. I am trying to define the component type for a variable as shown below: import MoreVert from '@material-ui/icons/MoreVert' import { SvgIconProps } from '@ ...

Is it necessary to install ng-bootstrap if my project was built using the Bootstrap 4 alpha theme in Angular 4?

I am currently utilizing the SB-Admin-BS4-Angular-4-master theme in Angular 4. The theme includes a link to . My goal is to implement Bootstrap modals in my code. Following the documentation provided in the theme, I integrated the modals as per instruction ...

The error message "TypeError: Attempting to access the 'map' property of an undefined value (React JS)" was displayed

I'm currently working on a recursive function that needs to iterate over an object type called ItemType. However, I encountered an error message: TypeError: Cannot read property 'map' of undefined This is the code snippet causing the issue: ...

Using multiple flatMap responses within the map operator across various functions: a guide

I've been working on a solution to connect multiple operations within a map function that follows the flatMap operator. Here's how it currently functions: flatMap( someResponse => combineLatest([ this.locator.function(someResponse, var ...

Guidelines for properly storing user data post-login in Nuxt3

When a user logs in, I need to store their data for future use. I have middleware set up on the "/page" page to check if the user is logged in, and if so, it allows them through. However, I notice that the user data is lost when the page is refreshed. In t ...

The PWA application is experiencing crashes on Safari following the recent IOS 17 update

Recently, I encountered an issue with my Angular app functioning as a PWA on my iPhone. Everything was working smoothly until the latest iOS 17 update. Now, the app crashes frequently and even when I clear the cache on Safari, it only works for a few min ...

Emphasize Text on an HTML Webpage

I am currently experimenting with the filter function to highlight specific search text. Take a look at the image below for reference. https://i.sstatic.net/I2yY0.png I have utilized ion-search from Ionic version 3 for this task. As shown in the code sn ...

Memory Leak in Angular's Chain of mergeMap and concatMap Functions

I am facing an issue where a memory leak is being caused for each processed file during the upload of a 1 TB folder to Blob Storage. I have implemented a parallel processing pipeline using mergeMap to handle the files through a series of steps with concatM ...

Warnings when compiling Angular with declarations of Angular Material components

Recently, I've been encountering numerous warnings during compilation after installing Angular Material. The warnings persist whether I install it directly from npm or through ng add @angular/material, regardless of whether I opt to use animations or ...

How can I retrieve the value of a promise in Promise.map?

I am currently working on a project that involves saving data to a database using Mongoose. One specific field in the database is the 'thumbnail' field, which needs to be filled with a base64 converted file after the file is uploaded to the serve ...