2

From a child component, using angular output, I am emitting a string value. What I want that, in the parent component, I will receive that string and will concatenate with the existing value.

parent component has a variable called customValue: string;

Now these peice of code is working customValue = customValue+ $event +' '

<parent>
 <child (stringValue)="customValue = customValue+ $event +' '"> </child>
</parent>

But if i try to concanate like this: customValue += $event +' ' then its not working.

<parent>
 <child (stringValue)="customValue += $event +' "> </child>
</parent>

Can someone please tell me why the above string concatenate is not working?

please note: I really do not want to create a function. Is there any way that without creating a function I can achieve what I desire for?

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Kazi
  • 1,461
  • 3
  • 19
  • 47
  • So your problem is really more "cosmetic" (size of output binding code) and to avoid repeating the name, right? What about creating a function for that? inspired from https://stackoverflow.com/questions/35731610/create-a-dynamic-variable-reference-in-typescript : in component: `public concatenateValue(field, toBeAdded) { this[field] += toBeAdded + ' '; }` in template `(stringValue)="concatenateValue('customValue', $event)"` – Pac0 Dec 10 '20 at 12:28
  • 1
    Ow sorry, I hadn't read the last part before my last comment: "I don't want to create a function". I don't understand why it's not ok. Could you please elaborate on the reason? – Pac0 Dec 10 '20 at 12:30
  • Actually there is no special reason. I thought it might be more cleaner not to create a function for just simple string concatenate. @Pac0 – Kazi Dec 10 '20 at 13:11
  • 1
    @Kazi Oh, I can understand the feeling, but after using Angular some time, I'd suggest the opposite. Code in template goes against the purpose of separating the UI from the logic of the component. Also, you get quicker compile-time issue feedback when you write code in a method than directly in template, where your code is just strings. – Pac0 Dec 10 '20 at 14:22

1 Answers1

3

From the angular docs:

The following JavaScript and template expression syntax is not allowed:

  • new

  • increment and decrement operators, ++ and -- operator

  • assignment, such as += and -=

  • the bitwise operators, such as | and & operator

Templates do not support some of the JavaScript features

meblum
  • 1,654
  • 12
  • 23