What is the best way to iterate over a nested array of objects and render them in my HTML using Angular/Ionic?

One of the challenges I'm facing involves working with an interface structured like this:

export interface SeriesCard {
  type: string,
  imageUrl: string,
  title: string,
  category: string,
  seriesItems: SeriesItems[];
}

Currently, my Service contains mocked data and my corresponding .ts file looks like this:

seriesCard: SeriesCard[];
  title: string = "";

  constructor(private navCtrl: NavController,
              private cardService: CardsService,
              private navExtraService: NavExtrasServiceService) { }

  navigateToPage(seriesItems: SeriesItems) {
    this.navExtraService.setExtras(seriesItems);
    this.navCtrl.navigateForward([`video-component`]);
  }

  ngOnInit() {
    this.seriesCard = this.cardService.getSeriesCardsArray();
    console.log(this.seriesCard);
  }

In the HTML file, I am using *ngFor to loop through my seriesCard as shown below:

<ion-content>
  <ion-grid class="ion-no-padding">
    <ion-row>
      <ion-col size="12" *ngFor="let cards of seriesCard; let i = index">
        <ion-list class="ion-list-background">
          <ion-item (click)="navigateToPage(cards.seriesItems[i])" class="ion-item-background" lines="none" style="border-bottom: 1px solid #343436;">
            <ion-avatar slot="start">
              <img src="{{cards.seriesItems[i].imageUrl}}" alt="">
            </ion-avatar>
            <ion-label>
              <h2 style="color: #ffffff">{{cards.seriesItems[i].title}}</h2>
              <ion-text class="smaller">{{cards.seriesItems[i].description}}</ion-text>
            </ion-label>
          </ion-item>
        </ion-list>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

The challenge arises when trying to iterate through the SeriesItems[] within each SeriesCard[]. The current implementation only loops at the top level rather than delving into the nested SeriesItems[].

Any suggestions on how I can overcome this hurdle?

I did attempt adding another *ngFor, but encountered some issues. Your input would be greatly appreciated.

UPDATE: I have already experimented with a second *ngFor. The intended outcome of the displayed HTML snippet is to showcase the number of SeriesItems within a single SeriesCard, meaning it should display 4 items and not 8!

Answer №1

In order to iterate over the array SeriesItems[], you will need to use another *ngFor directive within the <ion-item> tag.

<ion-item *ngFor="let seriesItem of cards.seriesItems">
    <ion-avatar slot="start">
       <img src="{{seriesItem.imageUrl}}" alt="">
    </ion-avatar>
    <ion-label>
       <h2 style="color: #ffffff">{{seriesItem.title}}</h2>
       <ion-text class="smaller">{{seriesItem.description}}</ion-text>
    </ion-label>
</ion-item>

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

Issue with TypeScript: Assigning type 'type' to 'IntrinsicAttributes & type & { children?: ReactNode; }' is not allowed. What is the solution?

I'm currently working on a small home project to enhance my skills in TypeScript. Everything was running smoothly with retrieving data from the server and displaying posts without any errors. However, when I decided to separate the code with the map i ...

Combine two Observable arrays into a single array and showcase their contents using ngFor within an Ionic 3 application

In my Ionic 3 project, I am fetching two arrays through API calls. My goal is to display the data from both arrays in the same line like this: [item1.1] [item2.1] [item1.2] [item2.2] [item1.3] [item2.3] Instead of displaying them like this: [item1.1] ...

Ways to troubleshoot and resolve the npx create-next-app issue

Every time I try to create a new app using npx create-next-app@latest --typescript, it keeps giving me this error message: npm ERR! code ENETUNREACH npm ERR! syscall connect npm ERR! errno ENETUNREACH npm ERR! request to https://registry.npmjs.org/create-n ...

Generate a distinctive example of the ionic 3 provider

I am currently developing an Ionic application and have 3 providers - database provider, portfolio provider, and user provider. All three are Injectable for easy access throughout the app. I structured it this way because multiple pages require their funct ...

Beta 8 of Angular Material 2 is causing MdDialog.afterAllClosed to return an undefined result instead of the expected data

I am currently facing an issue where the result from the dialog component's close method is returning as undefined. Could this be a bug present in angular material 2 beta 8? I have searched extensively online but have not been able to find any inform ...

Incorporating CASL with the latest version of Angular, version

I'm currently working on implementing CASL into my Angular application, but I'm having trouble understanding how to integrate it. // Login Component ngOnInit() { var jsonBody = {}; jsonBody['email'] = 'peter@klaven'; ...

TypeScript: Type narrowing issue when deconstructing an array within a function

I am working with an object that has a const assertion: const foo = { bar: ['a', 'b'], } as const; My objective is to create a function that can update the bar array and accurately infer the new type. I have successfully achieved th ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

Addressing the issue of potential null objects within an Angular FormGroup

While working on my Angular-15 project, I encountered an issue with the code in the component.ts file: component.ts: export class CountryCreateComponent { countriesData: any[] = []; selectedCountryCode: string = ''; selectedCountr ...

Unable to navigate using react-router after logging out without a page refresh

In my logout approach, everything seems to work fine - there are no errors in the console, localHistory is cleared successfully, but for some reason it cannot navigate to the login page without refreshing the current page. const handleLogout = () => { ...

"Organize your files with React and TypeScript using a file list

interface IVideos { lastModified: number, name: string, path: string, size: number, type: string, webkitRelativePath: string } const [videos, setVideos] = useState<IVideos[] | null>([]); <input type="file" onChange={(event) => ...

Angular displays X items in each row and column

I've been struggling with this task for the past 2 hours. My goal is to display a set of buttons on the screen, but I'm facing some challenges. The current layout of the buttons doesn't look quite right as they appear cluttered and unevenly ...

Tips on how to effectively simulate a custom asynchronous React hook that incorporates the useRef() function in jest and react-testing-library for retrieving result.current in a Typescript

I am looking for guidance on testing a custom hook that includes a reference and how to effectively mock the useRef() function. Can anyone provide insight on this? const useCustomHook = ( ref: () => React.RefObject<Iref> ): { initializedRef: ...

Could this type declaration in the Vue decorator constructor be accurate?

When using Vue decorator notation, I typically write it like this: @Prop({ type: Object || null, default: null }) However, I noticed in the Vue documentation that they use array notation: @Prop({ type: [ Object, null ], default: null }) Is there a specif ...

Discover additional information within extensive text by leveraging Angular 4 features

Looking for a solution to truncate text and limit it to 40 words, then display the full text when clicking on a "see more" link. I experimented with ng2-truncate, read-more-directive, and ng-text-truncate-2, but they were not compatible with Angular 4. ...

How can I adjust the indentation in Angular Prime-ng's p-tree component?

In my project, I am utilizing the primg-ng tree component for the sidebar. Currently, the output is displayed as shown here: https://i.stack.imgur.com/kcSQt.png However, I am looking to maintain consistent indentation levels without any adaptive changes ...

<T extends object>(value: T): T, but with the type changing from null to string

I discovered a tool called pathmirror that transforms objects like: {a: {b: null} } to {a: {b: 'a.b'} This is particularly useful for naming Redux actions. I'm wondering how I can create a type definition for this? Currently, my declarat ...

Exploring the difference between loop and stream patterns in Azure Service Bus message receiving operations

I am currently setting up the Azure Service Bus messaging infrastructure for my team, and I am working on establishing best practices for developing Service Bus message receivers. We are in the process of creating a new service to consume the Service Bus m ...

How to ensure Service is loaded before App Component in Angular 6?

My Data service is responsible for fetching the JSON Object value, however all components load before the data service finishes loading. This results in undefined values when I call the service method from components. ...

What are the steps to enable screen sharing within an Electron application?

I am currently working on developing two applications for screen sharing within a LAN setting using Electron, React, and TypeScript. The first app will capture the screen stream and broadcast it via UDP, while the second app, running on multiple devices, w ...