【问题标题】:How to restrict the data from JSON to table to certain rows in Angular?如何将 JSON 到表格的数据限制为 Angular 中的某些行?
【发布时间】:2020-09-30 17:35:33
【问题描述】:

我以 JSON 的形式从服务器中提取数据并将其添加到 HTML 表中。我想将表行修复为 5,并且只有 JSON 中的前 5 个值应该使用 Angular 进入表中。如果可用数据少于 5 个,请用“-”填充表格列。

component.ts

import { HttpClient } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-orderbook',
  templateUrl: './orderbook.component.html',
  styleUrls: ['./orderbook.component.css']
})
export class OrderbookComponent implements OnInit {
  title = 'JSON to Table Example';
  constructor (private httpService: HttpClient) { }
  arrBirds: string [];
  

  ngOnInit() {
    this.httpService.get('http://localhost:7000/orders/list').subscribe(
      data => {
        this.arrBirds = data as string [];   // FILL THE ARRAY WITH DATA.
         //console.log(this.arrBirds[1]);
      },
      (err: HttpErrorResponse) => {
        //console.log (err.message);
      }
    );
  }
  }

component.html

      <div style="text-align:left;width:500px;">
        <h1>
            {{ title }}!
        </h1>
        
        <table *ngIf="arrBirds">
            
              <tr>
                <th>Order ID</th>
                <th>Type</th>
                <th>Category</th>
                <th>Quantity</th>
                <th>Price</th>
              </tr>
          
          <tr *ngFor="let bird of arrBirds">
            <td>{{bird.orderId}}</td>
            <td>{{bird.type}}</td>
            <td>{{bird.category}}</td>
            <td>{{bird.quantity}}</td>
            <td>{{bird.price}}</td>
          </tr>
      </table>
    </div>

component.css

table {
    border-collapse: collapse;
    width: 95%;
    margin:0 0 0 20px;
  }
  
  table, th, td {
    border: 1px solid black;
  }

【问题讨论】:

    标签: javascript json angular


    【解决方案1】:

    实现此目的的一种简单方法是使用给定长度初始化数组:

    arrBirds = Array.from({length: 5});
    

    然后你可以将你的数据分配给这个数组

    if (data) {
        data.forEach((bird, index) => {
            this.arrBirds[index] = bird;
        });
    }
    

    稍微调整您的显示以处理空值:

              <tr *ngFor="let bird of arrBirds">
                <td>{{ bird?.orderId || '-' }}</td>
                <td>{{ bird?.type || '-' }}</td>
                <td>{{ bird?.category || '-' }}</td>
                <td>{{ bird?.quantity || '-' }}</td>
                <td>{{ bird?.price || '-' }}</td>
              </tr>
    

    你应该很高兴!

    【讨论】:

    • 我觉得这是最好的答案。很简单
    • 嗨,亚历克斯,感谢您的帮助。我尝试这样做,但它显示.forEach 的错误。所以我尝试在&lt;tr&gt; 标签中添加一个切片,它起作用了。 ``` ``` 但是现在如果 JSON 大小为 2,表格会向上移动。是否可以在剩余行中添加虚拟“-”以固定表格高度?
    • 为了防止这个错误,你应该强输入data参数:this.httpService.get('http://localhost:7000/orders/list').subscribe((data: string[]) =&gt; ...
    • 是的,它现在工作了。谢谢。关于如何添加虚拟行以保持行数固定的任何想法?行字段应填写“-”
    • 您是否尝试过使用Array.from({ length: 5}) 初始化您的数组?
    【解决方案2】:

    这种数据操作应该在组件中完成(或者最好是一个单独的服务)。

    您可以在 OrderbokComponent 中编写一个函数来获取前 5 名鸟类(根据您的自定义标准、价格/数量等),将其存储在一个变量中并使用它来生成列表。

    您甚至可以对 arrBirds 数组进行排序并在 ngFor 中执行类似的操作:

    <tr *ngFor="let bird of arrBirds | slice:0:4">
                <td>{{ bird?.orderId || '-' }}</td>
                <td>{{ bird?.type || '-' }}</td>
                <td>{{ bird?.category || '-' }}</td>
                <td>{{ bird?.quantity || '-' }}</td>
                <td>{{ bird?.price || '-' }}</td>
              </tr>
    

    【讨论】:

    • 嘿,这很好用。还有一个疑问是,如果说 JSON 大小只有 2,那么表格会向上移动。有什么方法可以为剩余的 3/5 行添加虚拟“-”?
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签