【问题标题】:Angular - Function on ngFor VariableAngular - ngFor 变量上的函数
【发布时间】:2018-08-28 15:32:14
【问题描述】:

假设我有 2 张桌子;书和作者。 Author 表包含对书籍 ID 的引用。

在 Angular 中,我想遍历作者,然后遍历该作者的书籍:

<div id="authors" *ngFor="let author of authors">
    <h1>{{author.name}}</h1>

    <div id="books" *ngFor="let book_id of author.books" ng-init="let book = getBook(book_id)">
        <h2>{{book.title}}</h2>
        .....
    </div>

</div>

这里的问题是 ng-init 不在 Angular 2+ 中。我需要能够运行一个函数才能从数据库中获取这本书,因为作者只持有对这本书的引用。

我已经看到了一些使用自定义指令的潜在解决方案。 12.

我的问题是,在这种情况下的最佳做法是什么? 或者是这种情况,我应该在早期阶段更好地处理数据?我这样做的原因是,如果我不需要某种类型的书,我可以隐藏(使用 ngIf)它们,而无需调用 DB 来获取书(效率更高?)。

我有点质疑指令解决方案,因为我很惊讶它没有内置在 Angular 中,因为这似乎是一个潜在的常见问题,除非他们希望你使用更好的解决方案。

【问题讨论】:

    标签: angular mean-stack


    【解决方案1】:

    你可以像https://alligator.io/angular/ngif-new-features-angular4/中的show一样使用“ngIf”

    <div id="authors" *ngFor="let author of authors">
        <h1>{{author.name}}</h1>
        <div id="books" *ngFor="let book_id of author.books">
           <ng-container *ngIf="getBook(book_id);let book">
            <h2>{{book.title}}</h2>
            .....
           <ng-container>
        </div>
    </div>
    

    但是在这个想法之间进行选择并转换数组

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 2020-10-25
      • 2018-10-20
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2017-11-10
      相关资源
      最近更新 更多