Jon*_*uhl 4 html html-table angular
我正在开发一个应用程序来显示使用 Java 的 TestNG 测试网站的结果。我知道这有点多余,因为 TestNG 已经生成了自己的网站,但它是训练营培训练习的一部分。
我在使用 生成表格时遇到了一个特殊问题*ngFor。问题是,如果测试返回失败,则会返回堆栈跟踪。由于 Java 堆栈跟踪非常冗长,因此该堆栈跟踪被放置在新行中,因此我无法像通常那样将 放在标记*ngFor上。<tr>我犹豫是否将其放在<tbody>标签上,因为我担心这会导致布局问题(确实如此),所以我尝试将两个<tr>标签包装在 a 中<div>并将其放在*ngFor上面。这不起作用,因为现在我的表标题与表的内容不对齐。我最终将*ngFor指令放在了 上,<tbody>因为这看起来基本上没问题,尽管它在我的行之间产生了一些伪影,就好像它们有边框一样。
但我仍然不喜欢这种方法。它不仅很糟糕,而且在非常大的布局上会产生一些错误。
<table class="table table-striped table-dark table-hover table-sm table-responsive" *ngIf="loaded">
<thead>
<tr>
<th>Name</th>
<th>Signature</th>
<th>Duration</th>
<th>Started At</th>
<th>Finished At</th>
<th>Status</th>
</tr>
</thead>
<tbody *ngFor="let method of testResults.tests; let index = index">
<tr>
<td>{{ method.name | camelToTitle }}</td>
<td>{{ method.signature }}</td>
<td>{{ method.duration_ms }} ms</td>
<td>{{ method.startTime | dates }}</td>
<td>{{ method.finishTime | dates }}</td>
<td
[ngStyle]="{ background: selectColor(method.status) }">
{{ method.status |passfail }}
</td>
</tr>
<tr>
<td *ngIf="method.exceptionClass != null" class="table-danger">{{ method.exceptionClass }}</td>
<td *ngIf="method.exceptionClass != null" colspan="5" class="table-danger">
<button class="btn btn-dark" (click)="toggleStackTrace(index)">{{ btnText }} Stack Trace</button>
<span class="font-weight-bold ml-1">Exception Message: {{ method.exceptionMessage }}</span>
<div *ngIf="method.showStackTrace">
<p [appStacktrace]="method.stackTrace"></p>
</div>
</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
本质上,我想做的是为每个运行的测试生成一行,并且,如果测试有堆栈跟踪,也为其生成一行。有没有一种好的、干净的方法来做到这一点?
做到这一点的最好方法是使用ng-container.
Angular 文档将 ng-container 描述为
不会干扰样式或布局的分组元素,因为 Angular 不会将其放入 DOM 中。
这允许您将 HTML 包装在ng-container标签中,如下所示:
<table class="table table-striped table-dark table-hover table-sm table-responsive" *ngIf="loaded">
<thead>
<tr>
<th>Name</th>
<th>Signature</th>
<th>Duration</th>
<th>Started At</th>
<th>Finished At</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<ng-container *ngFor="let method of testResults.tests; let index = index">
<tr>
<td>{{ method.name | camelToTitle }}</td>
<td>{{ method.signature }}</td>
<td>{{ method.duration_ms }} ms</td>
<td>{{ method.startTime | dates }}</td>
<td>{{ method.finishTime | dates }}</td>
<td
[ngStyle]="{ background: selectColor(method.status) }">
{{ method.status |passfail }}
</td>
</tr>
<tr>
<td *ngIf="method.exceptionClass != null" class="table-danger">{{ method.exceptionClass }}</td>
<td *ngIf="method.exceptionClass != null" colspan="5" class="table-danger">
<button class="btn btn-dark" (click)="toggleStackTrace(index)">{{ btnText }} Stack Trace</button>
<span class="font-weight-bold ml-1">Exception Message: {{ method.exceptionMessage }}</span>
<div *ngIf="method.showStackTrace">
<p [appStacktrace]="method.stackTrace"></p>
</div>
</td>
</tr>
</ng-container>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
的行为*ngFor得到维护,但 DOM 将只包含预期的标签(tbody、tr、td等)