Parse an array of objects in Angular, display specific fields at the template

Viewed 26

I would like to know how I can treat arrays of objects in Angular 14.1 and dispaly them at my html template. Following example given where I get an array of Movie objects returned:

media.component.ts

import { Component, OnInit } from '@angular/core';
import {environment} from "../../environments/environment";
import {HttpClient} from "@angular/common/http";


export interface RecentlyAddedMoviesResponse {
  results: Array<object>;
}



@Component({
  selector: 'app-media',
  templateUrl: './media.component.html',
  styleUrls: ['./media.component.css']
})
export class MediaComponent implements OnInit {

  public recently_added_movies: any[] = []

  constructor(private http: HttpClient) { }


  ngOnInit(): void {
    this.http.get<RecentlyAddedMoviesResponse>(environment.backend + '/api/v1/movies/recently_added').subscribe((RecentlyAddedMovies) => {
      console.log(RecentlyAddedMovies);
      this.recently_added_movies = RecentlyAddedMovies.results;
    });
  }
}

When I now look at my browsers console I see an Array [ {…} ] that contains all nesessary information I want to render at my Angulars html template. But how can I access the title field for example? I know this is quite basic but im still not getting trough :(

If I now run trough the object of the array at my template like so:

      <div *ngFor="let movie of recently_added_movies">
        <h1>{{movie.title}}</h1>
      </div>

I get back nothing at the template, only at the console. Why that?

Thanks in advance

1 Answers

You will neet to loop through your array in the template, which can be like this

<div *ngFor="let movie of recently_added_movies">
 {{movie.title}}
</div>

so, basically ngFor directive is all you need.

Update

Make sure the recently_added_movies array is correctly defined in the component script.

Example
interface Movie {title: string}

@Component()
class Movies implements OnInit {
  recently_added_movies: IMovie[] = [];
  constructor(private service: MovieService) {}
  ngOnInit(): void {
    this.service.getRecentlyAddedMovies()
        .subscribe(movies => this.recently_added_movies = movies);
  }
}
Related