IvanS95
IvanS95

Reputation: 5742

How to best dynamically show/hide string segments in Angular?

I'm building a template which may or may not have some values in it; let's say for example I need to build a URL string based on multiple fields coming from a JSON response.

<a class="url">{{ ad.domain }}/{{ ad.path1 }}/{{ ad.path2 }}...</a>

But I'm thinking on how to handle that case if some sections of the string are empty; like not having a value for path2 for example.

I could use an ng-container with and *ngIf directive inside the anchor tag but it ends up looking really messy and bloated:

<a class="url">{{ ad.domain }}<ng-container *ngIf="ad.path1 !== ''">/{{ ad.path1 }}</ng-container><ng-container *ngIf="ad.path2 !== ''">/{{ ad.path2 }}</ng-container>...</a>

It does get the job done, but I'm wondering if there's some other Angular way of doing this efficiently.

Upvotes: 0

Views: 443

Answers (1)

Zulqarnain Jalil
Zulqarnain Jalil

Reputation: 1691

use Ternary operator like this

<a class="url">{{ ad.domain+(ad.path1?'/'+ad.path1:'')+(ad.path2?'/'+ad.path2:'') }}</a>

Upvotes: 1

Related Questions