Sha*_*hdi 2 typescript angular angular-reactive-forms angular-forms angular6
我正在尝试构建跨越多个组件的Reactive-Form,就像这样
<form [formGroup]="myForm" (ngSubmit)="onSubmitted()">
<app-names></app-names>
<app-address></app-address>
<app-phones></app-phones>
<button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
当我尝试提交时,我得到空对象.
进行以下更改
1.仅使用一个FormGroup,而不是FormGroup为每个组件创建新的FormGroup .
你有@Input FormGroup但是你没有作为输入传递.
3. @Input从子组件中删除.
<form [formGroup]="myForm" (ngSubmit)="onSubmitted()">
<app-names [myForm]="myForm"></app-names>
<app-address [myForm]="myForm"></app-address>
<app-phones [myForm]="myForm"></app-phones>
<button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
import { Component, OnInit, Input} from '@angular/core';
import { FormControl, FormGroup,FormBuilder } from '@angular/forms';
@Component({
selector: 'app-address',
templateUrl: './address.component.html',
styleUrls: ['./address.component.css']
})
export class AddressComponent implements OnInit {
@Input() myForm: FormGroup;
constructor(
private formBuilder: FormBuilder
) { }
ngOnInit() {
this.myForm.addControl("homeAddress" , new FormControl());
this.myForm.addControl("officeAddress" , new FormControl());
}
}
Run Code Online (Sandbox Code Playgroud)
对其他组件进行类似的更改.
还有另一种选择可以不使用@Input
import { Component, OnInit } from '@angular/core';
import {
FormControl,
ControlContainer,
FormGroupDirective
} from '@angular/forms';
@Component({
selector: 'app-address',
templateUrl: './address.component.html',
styleUrls: ['./address.component.css'],
viewProviders: [
{
provide: ControlContainer,
useExisting: FormGroupDirective
}
]
})
export class AddressComponent implements OnInit {
constructor(private parent: FormGroupDirective) {}
ngOnInit() {
const myForm = this.parent.form;
myForm.addControl("homeAddress", new FormControl());
myForm.addControl("officeAddress", new FormControl());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2467 次 |
| 最近记录: |