1

I am trying to use Angular Dropdown. The JSON is as follows-

{
       { 
      "bookId":"1",
      "authors":{ "author1", "author2"}
       } 
       { 
      "bookId":"2",
      "authors":{ "author2", "author3"}
       } 
}

Have created a class named Book which stores the above values in Book Array named books.
In html code have the following -

 <select [(ngModel)]="book.id" (ngModelChange)='onBookSelected($event)'>  
            <option *ngFor="let book of books"
            [value] = "book.authors">{{book.id}}</option>
          </select>

In the component have the onBookSelected as follows-

onBookSelected(val: any)
{
  console.log(val);
}

I dont get the list of authors but get

[object Object],[object Object],[object Object]

I also tried creating an array of class author and using it as follows-

onBookSelected(authorList : any)
{
  console.log(authorList );
}

But get same output as

   [object Object],[object Object],[object Object]

Could someone please help to get list of authors when the book is selected from the dropdown. Thanks

1
  • Whats wrong with that? Author is an Object. Commented May 31, 2019 at 9:37

2 Answers 2

1

you need do some changes in order get the authors

<select [(ngModel)]="selectedBookId" (ngModelChange)='onBookSelected($event)'>  
            <option *ngFor="let book of books"
            [value] = "book.id">{{book.id}}</option>
</select>

and then in the onBookSelected($event)

component.ts

     let books=   {
           { 
          "bookId":"1",
          "authors":{ "author1", "author2"}
           } 
           { 
          "bookId":"2",
          "authors":{ "author2", "author3"}
           } 
     }

    onBookSelected(event){
       Object.values(this.books).forEach(book =>{
             if(book.bookId == this.selectedBookId){
                 console.log(Object.values(book.authors))
             }
       })
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Whats wrong with that? Authors is an Object. However it think you wanted it to be an array

  "authors":[ "author1", "author2"]

That would print normally in the console.

if you do

onBookSelected(authorList : any)
{
  console.log(JSON.stringify(authorList));
}

it will print what you expected.

1 Comment

I still get [object Object],[object Object],[object Object] on using JSON.stringify

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.