Angular 在反应式表单上进行所需的FormArray控制
我试图使表单字段成为被动表单的必需字段,但表单始终有效,我希望它在两个字段都不为空之前无效Angular 在反应式表单上进行所需的FormArray控制,angular,angular-reactive-forms,Angular,Angular Reactive Forms,我试图使表单字段成为被动表单的必需字段,但表单始终有效,我希望它在两个字段都不为空之前无效 从“@angular/core”导入{Component,VERSION,OnInit}; 从'@angular/forms'导入{Form,FormArray,FormBuilder,FormControl,FormGroup,Validators}; @组成部分({ 选择器:“我的应用程序”, templateUrl:“./app.component.html”, 样式URL:[“/app.comp
从“@angular/core”导入{Component,VERSION,OnInit};
从'@angular/forms'导入{Form,FormArray,FormBuilder,FormControl,FormGroup,Validators};
@组成部分({
选择器:“我的应用程序”,
templateUrl:“./app.component.html”,
样式URL:[“/app.component.css”]
})
导出类AppComponent实现OnInit{
name=“Angular”+VERSION.major;
testForm=this.fb.group({
问题:this.fb.array([
本集团(
[{testString:['']},验证器。必需],
[{testString:['']},验证器。必需]
)
])
});
构造函数(私有fb:FormBuilder){}
恩戈尼尼特(){
const control=this.testForm.get('questions')作为FormArray;
control.push(this.fb.group(
{
测试字符串:['']
},验证器。必填)
)
}
获取问题控件(){
将此.testForm.get('questions')作为FormArray返回;
}
}
表单是否有效:{{testForm.Valid}
FormBuilder方法期望controlConfig作为键值对,其中键是FormControl的名称,值是控件的配置
在您的示例中,您将无效的formControl配置传递给formgroup,这就是它始终有效的原因。按如下所示更改formGroup
组件。ts
testForm = this.fb.group({
questions: this.fb.array([
this.fb.group({
testString: ['',Validators.required]
})
])
});
然后在模板中,我们应该将testString键绑定到formControlName指令,如下所示:
<form [formGroup]="testForm">
<ng-container formArrayName="questions">
<ng-container *ngFor="let question of questionControls.controls; let i = index" [formGroupName]="i">
<input type="text" formControlName="testString" >
</ng-container>
</ng-container>
</form>
在FormArray中设置formGroup的方式是错误的。 您的FormGroup需要一个对象 请参见下面的示例:
我还删除了ngOnInit部分
export class AppComponent {
name = "Angular " + VERSION.major;
testForm = this.fb.group({
questions: this.fb.array([
this.fb.group(
{testString: new FormControl('', Validators.required)}
),
this.fb.group(
{testString: new FormControl('', Validators.required)}
),
])
});
constructor(private fb: FormBuilder) {}
get questionControls() {
return this.testForm.get('questions') as FormArray;
}
}
对于HTML,您需要一个FormGroupName和FormControlName。请参见下面的示例:
<form [formGroup]="testForm">
<ng-container formArrayName="questions">
<ng-container *ngFor="let question of questionControls.controls; let i = index">
<ng-container [formGroupName]="i">
<input formControlName="testString" />
</ng-container>
</ng-container>
</ng-container>
</form>
<form [formGroup]="testForm">
<ng-container formArrayName="questions">
<ng-container *ngFor="let question of questionControls.controls; let i = index">
<ng-container [formGroupName]="i">
<input formControlName="testString" />
</ng-container>
</ng-container>
</ng-container>
</form>