【问题标题】:Use ngFor in a Table inside of ng-template在 ng-template 内的表中使用 ngFor
【发布时间】:2021-04-30 09:40:44
【问题描述】:

我正在尝试遍历从 API 请求中获取的列表,并将数据插入到表中。我的问题是,该表位于 ng-template 标记内,我不知道如何处理。

这是我的代码:

<ng-template>
  <table>
    <thead>
      <tr>
        <th>Reference</th>
        <th>Chapter</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let ref of data">
        <td>{{ref.title}}</td>
        <td>{{ref.chapter}}</td>
      </tr>
    </tbody>
  </table>
</ng-template>

这是我的目标: Popover

【问题讨论】:

  • 为什么它在ng-template里面?
  • 因为,在弹出窗口中很合适

标签: angular ngfor ng-template


【解决方案1】:

如果你有一个变量“yourVariable”

一般来说你可以有一个

<ng-template #template1>
.... e.g. {{yourVariable|json}}..
</ng-template>

并使用

<ng-container *ngTemplateOutlet="template1"></ng-container>

你也可以使用

<ng-template #template2 let-data >
.... e.g. {{data|json}}..
</ng-template>

你在 *ngTemplateOutlet 中指明“上下文”

<ng-container *ngTemplateOutlet="template2; context:{$implicit:yourVariable}">
</ng-container>

看到,在这种情况下,模板内部的“数据”是“你的变量”

我不知道您的“弹出框”,但确定您的模板需要一个“模板引用变量”(上面代码中的“#template1”和“#template2”)

【讨论】:

    【解决方案2】:

    这是您的问题的解决方案:

    <hello name="{{ name }}"></hello>
    <p>
      Start editing to see some magic happen :)
    </p>
    
    <table>
      <thead>
        <tr>
          <th>Reference</th>
          <th>Chapter</th>
        </tr>
      </thead>
      <tbody>
        <ng-template ngFor let-ref [ngForOf]="data">
          <tr>
            <td>{{ref.title}}</td>
            <td>{{ref.chapter}}</td>
          </tr>
        </ng-template>
      </tbody>
    </table>
    

    和打字稿代码:

    import { Component, VERSION } from "@angular/core";
    
    @Component({
      selector: "my-app",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      name = "Angular " + VERSION.major;
      data = [
        {
          title: "title 1",
          chapter: "chapter1"
        },
        {
          title: "title 2",
          chapter: "chapter2"
        }
      ];
    }
    
    

    【讨论】:

    • 您可以直接添加代码而不是添加屏幕截图。
    • 我添加了源代码你可以查看。
    • 在这个例子中只有 tr 在 ng-template 里面。但我的问题是,是否也有可能整个表都在 ng-template 内?
    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2019-11-13
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    相关资源
    最近更新 更多