在Angular 2中使用* ngFor检查空值的最佳方法

时间:2016-12-06 11:05:31

标签: angular

我正在显示来自api的一些记录,并且一些结果为空,我想在响应值为空的情况下显示不同的值。如何才能做到最好?

以下是我的代码:

组件:

import {Component, OnInit} from '@angular/core';
import {PerformancesService} from '../../services/performances.service';
import {Performance} from '../../common/performance';

@Component({
    selector: 'performances',
    templateUrl: './app/components/performances/performances.component.html'
})

export class PerformancesComponent implements OnInit{
    performances: Performance[];

    constructor(private _service : PerformancesService){

    }

    getFunds(){
        this._service.getData().then(
            performances => this.performances = performances
        )
    }

    ngOnInit(){ 
        this.getFunds();
    }
}

模板:

<h2>Performance</h2>

<table class="table table-hover">
  <thead>
      <tr>
          <th>Fund Id</th>
          <th>Country Id</th>
          <th>1Mth</th>
          <th>3Mth</th>
          <th>YTD</th>
          <th>1Yr</th>
          <th>3Yrs</th>
          <th>5Yrs</th>
          <th>10Yrs</th>
      </tr>
  </thead>
  <tbody>
      <tr *ngFor="let performance of performances">
        <td>{{performance.id}}</td>
        <td>{{performance.country_id}}</td>
        <td>{{performance.OneMonthBack}}</td>
        <td>{{performance.ThreeMonthsBack}}</td>
        <td>{{performance.YearToDate}}</td>
        <td>{{performance.OneYearBack}}</td>
        <td>{{performance.ThreeYearsBack}}</td>
        <td>{{performance.FiveYearsBack}}</td>
        <td>{{performance.TenYearsBack}}</td>
      </tr>
  </tbody>
</table>

我不知道我是否可以在模板中执行此操作,或者我应该检查组件中的每个值。任何的想法? 谢谢!

4 个答案:

答案 0 :(得分:16)

没关系 - 这会检查数组是否为null,而不是数组中的元素。

您可以在*ngFor中进行空检查,而不是自定义管道,我认为它非常易读。如果performances为空,您只是提供一个空数组:

<tr *ngFor="let performance of (performances ? performances : [])">

答案 1 :(得分:10)

有多种方式。

  1. 检查内联并使用默认值,如@anshueVersatile所说:
  2. <tbody>
        <tr *ngFor="let performance of performances">
          <td>{{ (performance && performance.id) ? performance.id : 1337}}</td>
          ...
        </tr>
    </tbody>
    
    1. 你可以使用* ngIf:
    2. <tbody>
          <tr *ngFor="let performance of performances">
            <td *ngIf="performance && performance.id">{{ performance.id }}</td>
            <td *ngIf="!performance || !performance.id">default</td>
            ...
          </tr>
      </tbody>
      
      1. 使用管道并返回默认值:
      2. <tbody>
            <tr *ngFor="let performance of (performances | defaultValueIfNullPipe)">
              <td>{{ performance.id }}</td>
              ...
            </tr>
        </tbody>
        

        我个人更喜欢Pipe,因为它在你的模板中更加清晰。

答案 2 :(得分:0)

与||一起使用安全的导航运算符(?)操作员。比上述所有解决方案都更少的代码。

<tbody>
    <tr *ngFor="let performance of performances">
      <td>{{performance?.id || : 1234}}</td>
      ...
    </tr>
</tbody>

答案 3 :(得分:-1)

最简单的方法——使用初始化:

  projects: ProjectData[] = [];
  services: ServiceData[] = [];
  members: MemberData[] = [];

这将使 *ngFor 迭代零次。