将Angular 5与反应式表单一起使用,我尝试在不同组件的嵌套表单中创建嵌套表单:Main Form Component
包含Contact Component
,其中包含Address Component
。 Contact
和Address
个组件都包含FormGroup
。我能够进行一级嵌套工作(主表单和联系人),但Address
表单不起作用。
这是我迄今为止所做的尝试:
主要表格:
<form [formGroup]="testForm2">
<input formControlName="test2" />
<app-test-form [parent]="testForm2" formGroupName="testForm1"></app-test-form>
</form>
{{testForm2.value | json}}
export class TestFormFormComponent implements OnInit {
testForm2: FormGroup;
constructor() {
this.testForm2 = new FormGroup({
test2: new FormControl(),
testForm1: TestFormComponent.getFormGroup()
});
}
测试表格:
<div [formGroup]="parent">
<div [formGroupName]="formGroupName">
<input formControlName="test1" />
<app-address formGroupName="address" [parent]="testForm"></app-address>
</div>
</div>
export class TestFormComponent implements OnInit {
testForm: FormGroup;
@Input() parent: FormGroup;
@Input() formGroupName: string;
constructor() {
this.testForm = TestFormComponent.getFormGroup();
}
static getFormGroup(): FormGroup {
return new FormGroup({
test1: new FormControl(),
address: AddressComponent.getFormGroup()
});
}
ngOnInit() {
}
}
地址表格:
<div [formGroup]="parent">
<div [formGroupName]="formGroupName">
<mat-form-field>
<input matInput type="text" formControlName="address1" placeholder="Address Line 1" />
</mat-form-field>
<mat-form-field>
<input matInput type="text" formControlName="address2" placeholder="Address Line 2" />
</mat-form-field>
<mat-form-field>
<input matInput type="text" formControlName="city" placeholder="City" />
</mat-form-field>
<mat-form-field>
<mat-select formControlName="state" placeholder="State">
<mat-option *ngFor="let state of states" [value]="state.id">
{{ state.description | titlecase }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<input matInput type="text" formControlName="zip" placeholder="Zip" />
</mat-form-field>
</div>
</div>
export class AddressComponent implements OnInit {
states: Lookup[];
@Input() parent: FormGroup;
@Input() formGroupName: string;
constructor(private lookupServce: LookupService) {
}
static getFormGroup() {
return new FormGroup({
address1: new FormControl(),
address2: new FormControl(),
city: new FormControl(),
state: new FormControl(),
zip: new FormControl()
});
}
ngOnInit() {
this.lookupServce.lookupStates().subscribe(data => {
this.states = data;
});
}
}
输出:
{ "test2": "asdf", "testForm1": { "test1": "asdf", "address": { "address1": null, "address2": null, "city": null, "state": null, "zip": null } } }
如您所见,主窗体和测试窗体中的控件正在获取值,但即使在输入值后,地址窗体也为空。