Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a syntax for conditional template interpolation? [duplicate]

I have an angular (2.4.9) template with the following element:

<div *ngIf="a || b || c || d || e">Remaining</div>

I'm now faced with the need to change that hitherto static "Remaining" text based on another condition:

<div *ngIf="a || b || c || d || e || Z != 'draft'">Initial</div>
<div *ngIf="a || b || c || d || e || Z == 'draft'">Remaining</div>

The *ngIf is already loaded, and I'd like to prevent having to duplicate it, as I did in the example above, just to add that one extra condition.

I would also like to avoid doing this:

<div *ngIf="a || b || c || d || e">
    <div *ngIf="Z != 'draft'">Initial</div>
    <div *ngIf="Z == 'draft'">Remaining</div>
</div>

...because this changes the structure of the page and thus the style rules.

So, rather than introduce a new element within the div with its own *ngIf, which would cause us to add style rules, I was looking for something like a conditional interpolation syntax, such that I could write

<div *ngIf="many || conditions">{{ status === "DRAFT" ? 'Initial' : 'Remaining' }}</div>

in a similar way that you can do {{ 1 + 1 }}, which is also an expression which returns a value, so seems at least conceptually similar.

My attempt above causes the template parser to explode with an unmatched tag somewhere seemingly unrelated to this template, so what it's actually doing is not immediately apparent, but it's obviously incorrect.

like image 326
msanford Avatar asked Mar 30 '17 15:03

msanford


1 Answers

In Angular4 you can use else

<template #other>
  <div>Remaining</div>
</template>

<div *ngIf="a || b || c || d || e || Z != 'draft'; else other">Initial</div>

There is nothing for Angular2, except moving the expression to a getter or method and use that getter in *ngIf="..."

like image 105
Günter Zöchbauer Avatar answered Sep 18 '22 18:09

Günter Zöchbauer