Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

angular - Dividing a form into multiple components with validation

I want to create a single big form with angular 2. But I want to create this form with multiple components as the following example shows.

App component

<form novalidate #form1="ngForm" [formGroup]="myForm">
<div>
    <address></address>
</div>
<div>
    <input type="text" ngModel required/>
</div>

<input type="submit" [disabled]="!form1.form.valid" > </form>

Address component

<div>
<input type="text" ngModel required/> </div>

When I use the code above it was visible in the browser as i needed but the submit button was not disabled when I delete the text in address component.
But the button was disabled correctly when I delete the text in input box in app component.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would use a reactive form which works quite nicely, and as to your comment:

Is there any other simple example for this one? Maybe the same example without loops

I can give you an example. All you need to do, is to nest a FormGroup and pass that on to the child.

Let's say your form looks like this, and you want to pass address formgroup to child:

ngOnInit() {
  this.myForm = this.fb.group({
    name: [''],
    address: this.fb.group({ // create nested formgroup to pass to child
      street: [''],
      zip: ['']
    })
  })
}

Then in your parent, just pass the nested formgroup:

<address [address]="myForm.get('address')"></address>

In your child, use @Input for the nested formgroup:

@Input() address: FormGroup;

And in your template use [formGroup]:

<div [formGroup]="address">
  <input formControlName="street">
  <input formControlName="zip">
</div>

If you do not want to create an actual nested formgroup, you don't need to do that, you can just then pass the parent form to the child, so if your form looks like:

this.myForm = this.fb.group({
  name: [''],
  street: [''],
  zip: ['']
})

you can pass whatever controls you want. Using the same example as above, we would only like to show street and zip, the child component stays the same, but the child tag in template would then look like:

<address [address]="myForm"></address>

Here's a

Demo of first option, here's the second Demo

More info here about nested model-driven forms.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...