Moussa
Moussa

Reputation: 4154

AngularJS component for form

I have a form that contains different fields : input, select, select multiple, buttons. And I was wondering if it would be a good idea (and actually feasible) to create a component for this form, this component would be like a container that can contains all type of form fields (input, select, button, etc...).

I have put a sample of code on plunker, what I would like to do is to create a component for the form, in which I could insert how many other component I want (button, input, etc..).

<!DOCTYPE html>
<html ng-app="MyApp">

<head>
  <link data-require="[email protected]" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.6/angular.min.js"></script>
  <script src="script.js"></script>
  <script src="myInput.js"></script>
  <script src="myButton.js"></script>
</head>

<body ng-controller="MyCtrl">
  <div class="container">
    <h2>My form</h2>
    <form role="form">
      <my-input label="Firstname"></my-input>
      <my-input label="Lastname"></my-input>
      <my-button label="Submit"></my-button>
    </form>
  </div>
</body>

</html>

Upvotes: 1

Views: 321

Answers (2)

Prince John
Prince John

Reputation: 662

If you are planning to reuse the form in other parts of your code, I would say it would be a good idea to create it as a component.

Otherwise, it's just a matter of preference. Sometimes it can be nice to divide large portions of code into different files.

Edit: Plunker example https://plnkr.co/edit/kyt9Q6L01r06dJXLDQZH?p=preview

<body ng-controller="MyCtrl">
  <div class="container">
    <my-form></my-form>
  </div>
</body>

Edit 2: Updated the Plunker with an example of passing objects as attribute to the form

<body ng-controller="MyCtrl">
  <div class="container">
    <my-form inputlabels="inputs1"></my-form>
    <my-form inputlabels="inputs2"></my-form>
  </div>
</body>

Upvotes: 1

AranS
AranS

Reputation: 1891

If you mark "Yes" to these two questions then you should build a component:

  1. Is it reusable?
  2. Does the form has a unique logic?

Upvotes: 1

Related Questions