首页 > 解决方案 > 如何检查 ReportControl 对象上是否存在 Reportid 或不使用 *ngif?

问题描述

我在 Angular 7 应用程序上工作,我遇到了我需要检查的问题

使用 component.html 上的 *ngIf 在 Report Control 对象上是否存在 Reportid。

report.component.ts

displayreport: any = {};
Reportid: string;

ngOnInit() {
  this._displayreport.GetReportControl(Reportid).subscribe((res: any) => {
      this.ReportControl = res;
      console.log("report control is" + JSON.stringify(this.ReportControl)
      });
  }
}

this.ReportControl只返回一个对象:

{"reportid":"2040","reportName":"financialAsset","reportType":"1"}

预期结果:

*ngIf="???????"

标签: javascripttypescriptangular7angular-directiveangular-components

解决方案


displayreport: any = {};
Reportid: string;
ReportControl: any;
ngOnInit() {
  this._displayreport.GetReportControl(this.Reportid).subscribe((res: any) => {
      this.ReportControl = res;
      console.log("report control is" + JSON.stringify(this.ReportControl)
      });
  }
}

如果您reportid在 html(ngIf) 中的 response(res) 中检查该值是否可用,则可以通过以下方式实现:

  1. *ngIf="ReportControl && ReportControl.reportid"
  2. *ngIf="ReportControl?.reportid"

两者都以类似的方式工作,它们检查是否ReportControl存在,然后检查对应的是否reportid存在,这种方法更可靠,因为它避免了未定义的属性错误。


推荐阅读