猿问

如何以角度迭代对象数组

我有一个 BookArr 类书籍对象数组。


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在 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),

];

我想用html创建一个表格来显示这些书籍的详细信息。 books-list.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>


料青山看我应如是
浏览 132回答 4
4回答

LEATH

您已经在迭代 booksArr。只需要使用插值来显示数据。尝试这样<table border="1" *ngIf="bName">&nbsp; &nbsp; <thead>&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th>book ID</th>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th>book Name</th>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; </thead>&nbsp; &nbsp; <tbody>&nbsp; &nbsp; &nbsp; &nbsp; <tr *ngFor="let b of booksArr">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>{{b.bookId}}</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>{{b.bookName}}</td>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; </tbody></table>

海绵宝宝撒

您已经在使用 迭代书籍数组*ngFor="let b of booksArr"。您现在想要对数组中每本书的值进行插值。当您位于数组内部时,您可以访问在 中声明的循环变量*ngFor。在这种情况下,循环变量是b。b您现在可以绑定到使用大括号插值的属性。{{b.bookId}}。<table border="1" *ngIf="bName">&nbsp; <thead>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <th>book ID</th>&nbsp; &nbsp; &nbsp; <th>book Name</th>&nbsp; &nbsp; </tr>&nbsp; </thead>&nbsp; <tbody>&nbsp; &nbsp; <tr *ngFor="let b of booksArr">&nbsp; &nbsp; &nbsp; <td>{{b.bookId}}</td>&nbsp; &nbsp; &nbsp; <td>{{b.bookName}}</td>&nbsp; &nbsp; </tr>&nbsp; </tbody></table>

qq_遁去的一_1

在这种情况下不需要*ngIf。只需尝试以下操作<tbody>&nbsp; &nbsp; &nbsp; &nbsp; <tr *ngFor="let b of booksArr">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>{{b.bookId}}</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>{{b.bookName}}</td>&nbsp; &nbsp; &nbsp; &nbsp; </tr></tbody>在你的 .ts 文件中你应该改变constructor(bookId, bookName, cost, quantity)或者this.bookName=bookType;在你的构造函数中

catspeake

尝试:<td>&nbsp;{{&nbsp;b.bookId&nbsp;}}&nbsp;</td> <td>&nbsp;{{&nbsp;b.bookName&nbsp;}}&nbsp;</td>
随时随地看视频慕课网APP

相关分类

Html5
我要回答