问题描述
我正在尝试遍历从 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
解决方法
这是您问题的解决方案:
<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"
}
];
}
,
如果你有一个变量“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>
看到,在这种情况下,模板内部的“数据”是“你变量”
我不知道你的“popover”,但你肯定需要一个“模板引用变量”到你的模板(上面代码中的“#template1”和“#template2”)