You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中用ng-model结合Firestore在HTML表格展示数据的问题

问题分析与解决方案

嘿,我看了你的代码,马上发现几个导致表格不按预期显示的问题,咱们一步步来解决:

核心问题点

  1. 表格行的*ngFor与[(ngModel)]使用错误

    • 你现在表格里用*ngFor="let post of posts |async"会遍历所有Firestore返回的posts数据,这和你想要“选中某个用户后展示其对应数据”的需求不符。
    • 而且<tr>标签不能绑定[(ngModel)],这个指令是专门给输入框、下拉框这类表单控件用的,放在表格行上完全无效,还可能触发隐性错误。
  2. 表格列与数据对应关系错乱

    • 你的表头第一列是“Name”,但表格单元格里写的是{{ post.callDuration }},字段完全不匹配,这会导致显示内容和表头对不上。

针对性解决步骤

根据你的需求(选中下拉框用户后,表格展示该用户的对应数据),修正后的代码如下:

<!DOCTYPE html> 
<h1>Call Details Dashboard </h1> 
<label>Name:</label> 
<select [(ngModel)] = "selectedLevel" (change)="selected()" > 
  <option *ngFor="let post of posts | async" [ngValue]="post">{{post.user}} </option> 
</select> 

<table class="TFtable"> 
  <tr> 
    <th>Name</th> 
    <th>Duration</th> 
    <th>Time</th> 
    <th>Type</th> 
  </tr> 
  <!-- 用*ngIf避免未选中时显示空行,安全导航符?.防止空值报错 -->
  <tr *ngIf="selectedLevel"> 
    <td>{{ selectedLevel.user }}</td> 
    <td>{{ selectedLevel.callDuration }}</td> 
    <td>{{ selectedLevel.callTime }}</td> 
    <td>{{ selectedLevel.callType }}</td> 
  </tr> 
</table> 

<label>Duration:</label> 
<input type="text" name="callDuration" [(ngModel)]="selectedLevel.callDuration"> 

额外说明(如果需求是展示所有数据)

如果你原本想展示所有Firestore中的通话数据,那只需去掉表格行的错误绑定,修正字段对应关系即可:

<tr *ngFor="let post of posts | async"> 
  <td>{{ post.user }}</td> <!-- 对应Name表头 -->
  <td>{{ post.callDuration }}</td> 
  <td>{{ post.callTime }}</td> 
  <td>{{ post.callType }}</td> 
</tr>

如果需要下拉框做筛选功能,你可以在组件中用RxJS的filter操作符处理数据,或者自定义一个Angular管道来过滤posts集合。

内容的提问来源于stack exchange,提问作者ANUSHKA GARG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:42:31