Search code examples
javascripttypescriptangular7angular-directiveangular-components

How to check Reportid exist on ReportControl object or not using *ngif?


I work on angular 7 app I face issue I need to check

if Reportid exist or not on Report Control object using *ngIf on component.html.

on 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 return only one object as:

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

Expected result:

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

Solution

  • 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)
          });
      }
    }
    

    If you are checking if the value reportid is available in your response(res) in your html(ngIf), it can be achieved by following:

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

    Both work in a similar way, they check if ReportControl exists and then checks if corresponding reportid exists, this approach is more reliable as it avoids undefined property errors.