Search code examples
angulartypescriptangular-httpclient

display details of data in different component with help of its id in present component


service.ts

getAuthors() {
    this.authors=[{
      name:'raj',
      authorid:'3e32233edd222221'
      },{
      name:"roje",
      _id:"3e3223"
      }];
  }
  getBooks() {
    this.books=[{
      name:'2states',
      lang:'english',
      bookid:'123333',
      authorid:'3e32233edd222221'
      }];
  }

app.comp.html

<a *ngFor="let book of books">
  <p>{{book.name}}</p>
  <p>{{book.lang}}</p>
  <p>{{book.authorid}}</p> <!--this author id -->
  <p>{{author.name}}</p><!-- i need to show name with help 
  of authorid present in book -->
  </a>

In Above html i was displaying book details.I need author name to display with help of its id here is my setup https://stackblitz.com/edit/angular-859us9


Solution

  • Create a map of authors, which allows authorid based access to author's object:

    this.authorMap = this.authors.reduce((map, author) => {
      map[author.authorid] = author;
      return map;
    }, {});
    

    Now you can use this map in your template to render author's details:

    <p>{{book.authorid}}</p>
    <p>{{authorMap[book.authorid].name}}</p>