我有一个表格组。在表单组中,我有一个表单数组。我已经使用在初始化secretLairs FormArray一节中的反应形式的angular文档中描述的方法,使用数据模型中的数据创建的项初始化数组。问题是我需要对数组中的每个表单控件执行validation.required。但是,由于表单控件已经包含值,我不知道如何执行validation.required。文档没有进一步说明如何验证预先填充的formarray中的formcontrols。
以下是我的源代码:
html的
<!-- list of Questions -->
<div formArrayName="questions">
<!-- <div *ngFor="let que of Questions; let k=index"> -->
<div *ngFor="let question of Ques ; let i=index" [formGroupName]="i" >
<!-- The repeated questions template -->
<h4>{{question.ques}}</h4>
<div style="margin-left: 1em;">
<!-- <div class="form-group">
<label class="center-block">
<input class="form-control" formControlName="ques" >
</label>
</div> -->
<div class="form-group radio" *ngFor="let choice of
question.choices; let j = index">
<input type="radio" formControlName="choices"
class="custom-control-input" [value]="choice.choiceText">
<label>{{choice.choiceText}}</label>
</div>
<br>
<!-- End of the repeated questions template -->
</div>
</div>
</div>
<button type="submit" class="btn btn-danger"
[disabled]="!CheckListForm.valid">Submit</button>
</form>
.TS
export class CheckListFormComponent implements OnInit, OnChanges {
CheckListForm: FormGroup;
Ques: Questions[];
employmenttype = ['Permanent', 'contractor'];
constructor(private fb: FormBuilder,
private checklistservice: ChecklistService) {
this.CreateForm();
}
ngOnInit() {
this.checklistservice.getQuestions(1).subscribe(res =>{ this.Ques =res;
this.setquestions(this.Ques)
});
this.CheckListForm.get('EmploymentType').valueChanges.subscribe(
(EmploymentType: string) => {
if (EmploymentType === 'Permanent') {
this.CheckListForm.get('HRMS').setValidators([Validators.required]);
this.CheckListForm.get('CompanyName')
.setValidators([Validators.nullValidator]);
} else if (EmploymentType === 'contractor') {
this.CheckListForm.get('CompanyName').
setValidators([Validators.required]);
this.CheckListForm.get('HRMS').
setValidators([Validators.nullValidator]);
}
this.CheckListForm.get('HRMS').updateValueAndValidity();
this.CheckListForm.get('CompanyName').updateValueAndValidity();
}
)
}
CreateForm() {
this.CheckListForm = this.fb.group({
name: ['', Validators.required],
EmploymentType: ['', Validators.required],
HRMS: [''],
CompanyName:[''],
questions: this.fb.array([])
})
}
get questions(): FormArray {
return this.CheckListForm.get('questions') as FormArray;
}
setquestions(questions: Questions[]) {
const QuestionsFGs = questions.map(questions => this.fb.group(questions));
const QuestionsFormArray = this.fb.array(QuestionsFGs);
this.CheckListForm.setControl('questions', QuestionsFormArray);
}
答案 0 :(得分:0)
像往常一样,由于没有人回复,我会发布我辛苦解决的答案。
您无法通过我执行的方法验证表单控件(请参阅我的代码)。原因是因为表单控件已经保存数据并且首先不是空的。因此,validation.required将无效。
解决方案是为数据模型数组中的每个项目推送空的表单控件。
Validation.required将适用于此案例。