4

Feels like a dumb question but I do not get it. How can I do fast string concatenation in Angular 2 Dart templates?

I have a seperate html file for my component lets say my_component.html:

Works:

....
<div id="abc">
{{order.pickupPlace.email}}
</div>
...

Works:

....
<div id="abc">
{{ ((order.pickupPlace.state) ? order.pickupPlace.state+" ":'')}}
</div>
...

Does not work:

....
<div id="abc">
{{"<br/>"+order.pickupPlace.email}}
</div>
...

Does not work:

....
<div id="abc">
{{order.pickupPlace.name+" "+order.pickupPlace.email}}
</div>
...

Have tried to find an answer in the docs here (https://webdev.dartlang.org/angular/guide/template-syntax#!#expression-operators) but no luck.

Of course I could use *ngIf on every element which I output conditionally but is there a way for simple string concatenation?

Blackbam
  • 17,496
  • 26
  • 97
  • 150
  • 1
    I don't see why these "Does not work" examples would not work. Do you get an error? `
    ` in `{{...}}` won't work though because it will be added as text, not as markup.
    – Günter Zöchbauer Mar 21 '17 at 20:54
  • Must check when back to the project. So you think for Strings only it should work and for markup I have to use `*ngIf` ? – Blackbam Mar 21 '17 at 21:00
  • 1
    For markup you can use something like `
    "` but I guess `<` and `>` in a literal string inside the template won't work because it invalidates the templates HTML. You can use markup if it is stored in a variable though and also do concatenation inside the template.
    – Günter Zöchbauer Mar 21 '17 at 21:02

2 Answers2

5

The best way is to declare a getter inside your Component controller that does the concatenation for you, you will get dart syntax support and the html template will looks cleaner.

String get myConcatenation => "${order.pickupPlace.name}${order.pickupPlace.email}";


<div id="abc">
   {{myConcatenation}}
</div>
Hadrien Lejard
  • 5,644
  • 2
  • 21
  • 18
  • Upvote but in a top level component I may end up with very much getters which blow the controller .. is there another way? – Blackbam Mar 21 '17 at 20:17
  • what error do you have with the two last examples ?, like Günter said, `
    ` inside `{{...}}` wont' work, `
    ` should be outside
    – Hadrien Lejard Mar 21 '17 at 20:56
4

The last two examples can be made to work easily:

<div id="abc">
  <br/>{{order.pickupPlace.email}}
</div>

And:

<div id="abc">
  {{order.pickupPlace.name}} {{order.pickupPlace.email}}
</div>

Angular handles this pretty well. If you need some more complicated logic you can move it to the Dart code (but you cannot use HTML there easily).

If you find creating lot of weird logic consider creating more smaller components that can handle this for you.

rkj
  • 8,787
  • 2
  • 29
  • 35