5

I have this line of code

<a href="{{banner.url}}"></a>

But sometimes url is null. How can I check it for null and then pass url to href?

I've tried this

<a href="{{banner.url === null ? javascript:void(0) : banner.url}}"></a>

But it throws an error

zone.js:388 Unhandled Promise rejection: Template parse errors:
Parser Error: Got interpolation ({{}}) where expression was expected at column 0 in [{{banner.url === null ? javascript:void(0) : banner.url}}]
gsiradze
  • 4,583
  • 15
  • 64
  • 111

3 Answers3

6
<a [href]="banner.url === null ? 'javascript:void(0)' | safeUrl : banner.url"

With safeUrl being a pipe like shown in https://stackoverflow.com/a/37076868/217408

otherwise javascript:void(0) probably won't be added for security reasons (not tried myself)

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0
<a href="{{banner?.url || '#'}}"></a>

change # with your default URL

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
0

Use ternary operator in interpolation.

<a href="{{banner?.url === null ? 'javascript:void(0)': banner.url }}"></a>
Nitin Lawande
  • 563
  • 1
  • 4
  • 8