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?

4
  • 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 stackoverflow.com/questions/35731610/… : in component: public concatenateValue(field, toBeAdded) { this[field] += toBeAdded + ' '; } in template (stringValue)="concatenateValue('customValue', $event)" Commented Dec 10, 2020 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? Commented Dec 10, 2020 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 Commented Dec 10, 2020 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. Commented Dec 10, 2020 at 14:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.