Javascript 检查ngFor循环中的空值

Javascript 检查ngFor循环中的空值,javascript,html,angularjs,angular,Javascript,Html,Angularjs,Angular,我正在网页的按钮中显示信息。按钮显示列表中的多个对象及其字段(例如object.name、object.age等)。在某些情况下,其中一个字段为空。如何检查值是否为null?如果为空,我想打印“未知”-到目前为止,它不打印任何内容 以下是我的ngFor循环(在我的例子中,环境有时为空): 管道是一个很好的解决方案,但如果需要,可以直接在html中使用*ngIf: <button *ngFor="let object of objects; let i = index" type="butt

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

以下是我的ngFor循环(在我的例子中,环境有时为空):


管道是一个很好的解决方案,但如果需要,可以直接在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>

管道是一个很好的解决方案,但如果需要,可以直接在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>

以下是管道的外观:

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
。。。

环境:{{object.environment | unknown}}//这是您在@Pipe decorator中输入的任何名称

就我个人而言,我更喜欢管道,因为它留下了更清晰、可读性更强的html,并充分利用了您正在编码的框架

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
。。。

环境:{{object.environment | unknown}}//这是您在@Pipe decorator中输入的任何名称

就我个人而言,我更喜欢管道,因为它使用更干净、可读性更强的html,并充分利用了您正在编写的框架

这听起来像是对a的一个很好的使用这听起来像是对a的一个很好的使用