简体   繁体   English

如何以角度迭代对象数组

[英]How to iterate through an array of objects in angular

I have an array booksArr of objects of class book.我有一个类 book 对象的数组 booksArr 。

book.ts class book.ts 类

export class Book{
bookId:number;
bookName:string;
cost:number;
quantity:number;
constructor(bookId, bookType, cost, quantity){
    this.cost=cost;
    this.bookId=bookId;
    this.bookName=bookName;
    this.quantity=quantity;
}}

booksArr in books-list.component.ts bookArr在books-list.component.ts 中

   booksArr: book[] = [
    new book(100, "The Alchemist", 20, 1),
    new book(101, "Rich Dad Poor Dad", 50, 2),
    new book(102, "Charolett's Web", 10, 1),
    new book(103, "Harry Potter", 70, 4),
    new book(104, "Gone Girl", 150, 3),
];

I want to create a table in html to display the details of these books.我想在html中创建一个表格来显示这些书籍的详细信息。 books-list.component.html书籍列表.component.html

<table border="1" *ngIf="bName">
    <thead>
      <tr>
        <th>book ID</th>
        <th>book Name</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let b of booksArr">
        <td *ngIf="b.//WHAT SHOULD I PUT HERE"</td>
      </tr>
    </tbody>
  </table>

Try:尝试:

<td> {{ b.bookId }} </td>
<td> {{ b.bookName }} </td>

You are already iterating the array of books with *ngFor="let b of booksArr" .您已经在使用*ngFor="let b of booksArr"迭代书籍数组。

You want to now interpolate the values from each book in the array.您现在想要插入数组中每本书的值。 When you are inside the array, you have access to the loop variable you declare in *ngFor .当您在数组中时,您可以访问您在*ngFor声明的循环变量。 In this case the loop variable is b .在这种情况下,循环变量是b You can now bind to the properties on b using curly brace interpolation.您现在可以使用花括号插值绑定到b上的属性。 {{b.bookId}} . {{b.bookId}}

<table border="1" *ngIf="bName">
  <thead>
    <tr>
      <th>book ID</th>
      <th>book Name</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let b of booksArr">
      <td>{{b.bookId}}</td>
      <td>{{b.bookName}}</td>
    </tr>
  </tbody>
</table>

You are already iterating through the booksArr.just need to use interpolation to display the data.您已经在遍历 booksArr。只需要使用插值来显示数据。 Try like this像这样尝试

<table border="1" *ngIf="bName">
    <thead>
        <tr>
            <th>book ID</th>
            <th>book Name</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let b of booksArr">
            <td>{{b.bookId}}</td>
            <td>{{b.bookName}}</td>
        </tr>
    </tbody>
</table>

No *ngIf is required in this case.在这种情况下不需要*ngIf Just try the following只需尝试以下

<tbody>
        <tr *ngFor="let b of booksArr">
            <td>{{b.bookId}}</td>
            <td>{{b.bookName}}</td>
        </tr>
</tbody>

And in your .ts file you should either change在您的 .ts 文件中,您应该更改

constructor(bookId, bookName, cost, quantity)

Or或者

this.bookName=bookType;

inside your constructor在你的构造函数里面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM