【问题标题】:Check for null value in ngFor loop检查 ngFor 循环中的空值
【发布时间】:2016-11-07 13:04:27
【问题描述】:

我正在网页的按钮中显示信息。这些按钮显示列表中的多个对象及其字段(例如 object.name、object.age 等)。在某些情况下,这些字段之一为空。如何检查一个值是否为空?如果它为空,我想打印“未知” - 到目前为止它什么也没打印。

这是我的 ngFor 循环(在我的情况下,环境有时为空):

<button *ngFor="let object of objects; let i = index" type="button" style="text-align:left; margin-right: 10px; margin-bottom: 10px" class="btn btn-primary"
        Name: {{object.name}} <br /> Locations: {{object.date}} <br /> Environments: {{object.environment}}
</button>

我知道我可以手动将环境设置为“未知”,因为它是一个字符串值,但我想知道是否有办法通过 html 来做到这一点。

【问题讨论】:

  • 这听起来很适合pipe

标签: javascript html angularjs angular


【解决方案1】:

这是你的管道的样子:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'unknown'})
export class Unknown implements PipeTransform {
  transform(value: any): any {
    return value ? value : 'Unknown'
  }
}

在您的组件中,您需要包含管道:

@Component({
...
pipes: [Unknown] // this is whatever you named your exported class

然后在你的 html 中你会有

...
<br /> Environments: {{object.environment | unknown}} //this is whatever name you put in the @Pipe decorator

就我个人而言,我更喜欢管道,因为它可以让 html 更清晰易读,并充分利用您正在编码的框架

【讨论】:

    【解决方案2】:

    管道是一个很好的解决方案,但如果您愿意,可以直接在 html 中使用 *ngIf:

    <button *ngFor="let object of objects; let i = index" type="button" style="text-align:left; margin-right: 10px; margin-bottom: 10px" class="btn btn-primary"
        Name: <span *ngIf="object.name">{{object.name}}</span> <span *ngIf="!object.name">Unknown</span>
    

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 2011-01-16
      • 2018-05-22
      • 2021-11-17
      • 1970-01-01
      • 2012-03-01
      • 2021-09-08
      • 2016-08-31
      • 2013-03-27
      相关资源
      最近更新 更多