How to show data in view only if its value is > 0 in Angular

时间:2019-04-08 12:46:40

标签: angular

I have some data from a web api coming in, I want to show the data only if its value is more than 0 so far what I am doing is not achieving this, which is:

example data structure:

result: Array(1)
0:
element: "xxxxx"
element_id: "xxxx"
name: "xxxxx"
etc etc etc

component.ts

receivedIncidentComments: any;

constructor(private service: nowService,
    private appComponent: AppComponent,
    private userService: UserService,
    private router: Router,
    private http: HttpClient,
    private route: ActivatedRoute
  ) {
    this.receivedIncidentComments = { created_on: '', value: ''}
  }

private getIncidentComments() {
  this.service.getIncidentComments(this.customer_id, this.sys_id).subscribe((data) => {
    console.log('Result - ', data);
    console.log('comments are received');
    this.receivedIncidentComments = data.result[0];
  })
}

ngOnInit() {
    this.getIncident();
    this.getIncidentComments();
      })
  }

}

service.ts

 getIncidentComments(customerId, sys_id): Observable<any> {
    return this.http.get<any>(this.commentsApiUrl + "?customer_id=" + customerId + "&incident_id=" + sys_id)
       .pipe(
         catchError(this.handleError)
       );
   }

html:

<ng-container *ngIf="receivedIncidentComments.length > 0">
   <div class="information-text">
      <h5>Comments:</h5>
      <span class="text-gray">{{receivedIncidentComments.created_on}}</span><br />
      <span class="text-gray">{{receivedIncidentComments.value}}</span>
   </div>
</ng-container>

Any ideas?

4 个答案:

答案 0 :(得分:1)

replace

<ng-container *ngIf="data.length > 0">

with

<ng-container *ngIf="receivedIncidentComments">

答案 1 :(得分:0)

Try this:

<ng-container *ngIf="receivedIncidentComments.length > 0">
   <div class="information-text">
      <h5>Comments:</h5>
      <span class="text-gray">{{receivedIncidentComments.created_on}}</span><br />
      <span class="text-gray">{{receivedIncidentComments.value}}</span>
   </div>
</ng-container>

答案 2 :(得分:0)

You need to provide some more info. Are you storing the incoming data in an instance variable ? receivedIncidentComments? in that case

*ngIf="receivedIncidentComments.length > 0"

your syntax of the *ngIf directive is correct. With can mean you are not constructing your boolean/logic statement with the correct members. Please share the entire TS and HTML file :)

答案 3 :(得分:0)

从您的html结构中可以很明显地看到ReceivedIncidentComments是一个对象。 因此,要查找对象的长度,可以使用以下

Object.keys(receivedIncidentComments).length;

希望您现在可以实现自己的逻辑。 您可以简单地将对象长度存储在component.ts文件中。 现在用于检查html 您可以按以下方式使用它。

*ngIf = "your_variable > 0"