C
C
Coder3212016-11-22 16:42:09
Angular
Coder321, 2016-11-22 16:42:09

Custom components in Angular 2 form?

I have a large form that has more than 10 inputs. Is it possible to break all the inputs into components while retaining the functionality of the FormBuilder ?
So now:

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
    <div class="inlineBlock">
      <label for="titleInput">Title</label>
      <input type="text" id="titleInput" placeholder="Title" [formControl]="myForm.get('title')" [(ngModel)]="title">
    </div>
    <button type="submit">Submit</button>
  </form>

So I would like:
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
        <my-title-component></ my-title-component>
    <button type="submit">Submit</button>
  </form>

<!--my-title-component template-->
    <div class="inlineBlock">
      <label for="titleInput">Title</label>
      <input type="text" id="titleInput" placeholder="Title" [formControl]="myForm.get('title')" [(ngModel)]="title">
    </div>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
SergeyBugai, 2017-01-29
@Coder321

Let's say you create a form group with one more nested group:

this.myForm= this.fb.group({
      'checboxGroup': this.fb.group({
        'first': [false],
        'second': [false]
      })
    });

And then it simply passes the input as a parameter to the nested group in your component:
in my-title-component :
That's it)

V
Vitaly, 2016-11-22
@vitali1995

Most likely, you do not understand the architecture of your application. In Angular 2, all independent sections that have a completed assignment and can be reused are taken out into a separate component. If there are many properties that are displayed in a similar way, it is better to iterate over them in a loop. If you get a large form with unique fields, there is nothing wrong with putting the template into one hefty html file.

R
Ruslan Lopatin, 2016-11-23
@lorus

You can break it, but the controls from nested components will not be registered in the main form. Thus, validation, for example, will not work. And just adding them to the form will not work. So either put up with it, or use all sorts of cunning workarounds. I have not seen a ready solution. More about the issue here: https://github.com/angular/angular/issues/12504

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question