Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: If value exists show html

At the moment i have a service that pulls values from a number of APIs that I have written. In the template i wish to only output the following html if the value exists or is not empty in the results when they are fed to the template:

<li class="title rh-blue-lite-fg">{{ project.meta_header_one }}</li>

so I am trying to figure out how to wrap this in ngIf or is there some other way to do this so that this 'li' item only gets output if that value is present and not empty

like image 417
Kravitz Avatar asked Apr 22 '26 07:04

Kravitz


2 Answers

I think you can use ngIF directive to check if project isn't null:

<li class="title rh-blue-lite-fg" *ngIf="project.meta_header_one">{{ project.meta_header_one }}</li>

Reference: https://angular.io/docs/ts/latest/api/common/index/NgIf-directive.html

like image 175
Kayo Lima Avatar answered Apr 23 '26 22:04

Kayo Lima


Angular 4+

Using Angular 4 or later (at least up to Angular 6) you can use *ngIf with the as keyword to store the condition value in a variable like this:

<div *ngIf="condition as value">{{value}}</div>

This way you don't have to repeat the condition, which can be useful if the expression is long or contains method calls that you want to avoid calling more than once.

Applied to the code snippet from the question:

<li class="title rh-blue-lite-fg" *ngIf="project.meta_header_one as value">{{value}}</li>

Reference: *NgIf API Documentation

like image 23
Niemi Avatar answered Apr 23 '26 22:04

Niemi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!