在Angular 2中添加嵌套表单可以通过使用FormGroup和FormArray来实现。以下是一个完整的步骤:
<form [formGroup]="myForm">
<!-- 表单控件 -->
</form>
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
myForm: FormGroup;
ngOnInit() {
this.myForm = new FormGroup({
nestedForm: new FormGroup({
// 嵌套表单控件
})
});
}
}
<form [formGroup]="myForm">
<div formGroupName="nestedForm">
<input formControlName="nestedControl">
</div>
</form>
<form [formGroup]="myForm">
<div formArrayName="nestedForms">
<div *ngFor="let nestedForm of myForm.get('nestedForms').controls; let i=index" [formGroupName]="i">
<input formControlName="nestedControl">
</div>
</div>
</form>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.myForm = this.formBuilder.group({
nestedForms: this.formBuilder.array([
this.formBuilder.group({
nestedControl: ''
})
])
});
}
get nestedForms() {
return this.myForm.get('nestedForms') as FormArray;
}
addNestedForm() {
this.nestedForms.push(this.formBuilder.group({
nestedControl: ''
}));
}
}
<form [formGroup]="myForm">
<div formArrayName="nestedForms">
<div *ngFor="let nestedForm of nestedForms.controls; let i=index" [formGroupName]="i">
<input formControlName="nestedControl">
</div>
</div>
<button (click)="addNestedForm()">添加嵌套表单</button>
</form>
这样,你就可以在Angular 2中添加嵌套表单了。请注意,以上示例中使用的是Angular的响应式表单,需要在组件中导入ReactiveFormsModule。另外,你可以根据具体需求自定义表单控件和验证器。
领取专属 10元无门槛券
手把手带您无忧上云