How do you use Angular databinding to output nested data?

I will have multiple timeslots, each with multiple windows. I understand the basic concept of databinding but can not seem to get it to work with nested arrays. I’ve tried it several ways to no avail. Not sure what I’m doing wrong.

export interface Timeslot {
    from: Date;
    to: Date;
    sunday: boolean;
    monday: boolean;
    tuesday: boolean;
    wednesday: boolean;
    thursday: boolean;
    friday: boolean;
    saturday: boolean;
    windows: Window[];
}

export interface Window {
    from: any;
    to: any;
    maxAvailability: number;
    isOpen: boolean;
}
timeslots: Timeslot[] = [
    {
        from: new Date("January 01, 1990 10:05:00"),
        to: new Date("December 31, 2021 10:05:00"),
        sunday: false,
        monday: true,
        tuesday: true,
        wednesday: true,
        thursday: true,
        friday: true,
        saturday: false,
        windows: [
            {
                from: "8:00",
                to:   "12:00",
                maxAvailability: 100,
                isOpen: true
            },
            {
                from: "12:00",
                to:   "4:00",
                maxAvailability: 80,
                isOpen: true
            },
            {
                from: "4:00",
                to:   "9:00",
                maxAvailability: 80,
                isOpen: true
            },
        ]
    }
];

How come I can’t use something like {{ timeslot.windows.from }} to output nested data? How should I go about it instead?

Also, how would I go about outputting the total number of windows? In this case, 3. Something like {{ timeslot.windows.length }}.

16 thoughts on “How do you use Angular databinding to output nested data?”

  1. You can’t use {{ timeslot.windows.from }} because it is an array. How do you expect Angular to guess which items of your array it should pick to display data ? For this to work, you’ll need to use an *ngFor to loop over your array, something like :

    // First loop over timeslot
    <div *ngFor="let slot of timeslot>
      // Then loop over windows inside each slot
      <div *ngFor="let item of slot.windows">
        {{items.from}}
      </div>
    </div>
    

    If you want to display a specific items’s data, then you can simply precise its index in the array like {{timeslot.windows[0].from}}.

    Reply
  2. In your case, I’d say the problem is your data structure (and not angular). timeslot.windows is an array, therefore you can only access array elements by index.

    {{ timeslot.windows[index].from }} should works.

    You can also loop through your windows by using *ngFor.

    <ul>
      <li *ngFor="let window of timeslot.windows">{{ window.from }}</li>
    </ul>
    
    Reply

Leave a Comment