Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn my form into an ember component?

I have this form:

<form {{action 'resetPassword' on="submit"}}>
  {{input type="password" value=newPassword placeholder="reset password"}}<br>
  {{#if newPassword}}
    {{input type="password" value=confirmPassword placeholder="confirm password"}}
    {{#if passwordOK}}
      <button>Reset</button>
    {{/if}}
  {{/if}}
</form>

It relies on the resetPassword action being available and also the passwordOK function which tests that a password has been entered and that the confirmation matches.

This is all smashing but I think I need to use this form multiple times in my app. So I assume I should make it into a component.

How can I turn this form into a reusable component?

I'm interested in how to take this chunk of functionality and make it available throughout my app. How do I package this up and re-use it?

like image 447
Graeme Stuart Avatar asked Nov 20 '25 20:11

Graeme Stuart


1 Answers

Possibly late for this party but it may help someone else.

A 5 Minute Guide to Creating an Ember Form Component With Ember CLI

  1. Generate a new project - "ember new quick-form"
  2. Navigate into that directory then type - "ember g component password-component"
  3. In your project directory, go to app > components > password-component.js. There, replace the code with this:

    import Ember from 'ember';
    
    export default Ember.Component.extend({  
      passwordOK: function(){
        return this.get('newPassword')===this.get('confirmPassword');
         }.property('newPassword','confirmPassword'),
    
    actions: {  
    resetPassword: function() {  
      alert(this.get('newPassword'));  
        }    
      }  
    });  
    
  4. Go to app > templates > components > password-component. There, replace the {{yield}} with this:

    <form {{action 'resetPassword' on="submit"}}>  
      {{input type="password" value=newPassword placeholder="reset password"}}<br>  
        {{#if newPassword}}  
          {{input type="password" value=confirmPassword placeholder="confirm password"}}  
            {{#if passwordOK}}  
              {{input type="submit" value="submit"}}  
            {{else}}  
            passwords don't match  
            {{/if}}    
        {{/if}}  
    </form>  
    
  5. In app > templates > application.hbs, add the component you've just created by simply adding this: "{{password-component}}"

  6. Build your project ("ember s")

  7. Your component should be visible. Adding content to the input field and clicking on submit, should show up the contents of what you just typed in.

like image 59
learningMachine Avatar answered Nov 24 '25 04:11

learningMachine