koanima
koanima

Reputation: 577

How can you use the value generated in a component in the form of the parent in Emberjs?

In my Ember.js app, there is a template with a form for multiple lines of user input. One of the input items is a complicated setup that I want to re-use, so I put it in a component. When the user submits the form though, the value from the component does not get sent. How can I do this?

For example, this is the template with the main form:

<script type='text/x-handlebars' data-template-name='userForm'>
   // multiple inputs like this in the main template:
   {{view Ember.TextField valueBinding="newName"}}

   // and then I bring in the component:
   {{profile-details}}
   <button {{action addEntry}}>Add</button>
</script>

The component template contains input fields as well, such as:

{{input type='text' value=number valueBinding="monitor"}}

What I'd like to happen is that when the user clicks the button in the template, invoking the addEntry action, the values from the component inputs go along with the template's inputs to the userForm Controller. How can I do that? Thanks

Upvotes: 0

Views: 148

Answers (1)

Sherwin Yu
Sherwin Yu

Reputation: 3230

Just like you can pass in bindings to views, you can pass them in to components as well. So the short answer is, you would declare an additional property (let's call it profileInformation), which you pass into the profile-details component. Any interaction on the profile-details component automatically synchronizes profileInformation to the rest of your app.

Then, in whatever function is handling the addEntry action, you can directly reference your profileInformation variablee.

So for instance:

In your template:

{{view Ember.TextField valueBinding="newName"}}
{{profile-details profileInformationBinding="myProfileInformation"}}
<button {{action addEntry}}>Add</button>

And in your controller:

actions:
  addEntry: ->
    # @get('myProfileInformation') --- you can access the details directly.

And in your component, you would have to write the logic that makes sure profileInformation remains updated. I don't know exactly what's in ProfileDetailsComponent, but it could be something like a computed property that concatenates a bunch of different values derived from the component.

Note that in this example, profileInformation is the property your component sees, whereas myProfileInformation is property that the rest of your app sees. They could, of course, be named the same.

Upvotes: 1

Related Questions