typescript - 基于单选按钮选择验证 Angular 表单控件
我有一个表单,其中某些字段只有在某个问题回答为是时才会显示。因此,如果答案为是,这些表单控件必须进行验证。但在我的表单中发生的情况是,如果这些字段未填写,表单就会变为无效。以下是我的代码:
<label for="DSYesNo"><h3> Does you need to access other Data? </h3> </label>
<div *ngFor="let obj of yesNoArray">
<input type="radio" class="form-control" name="DSYesNo" value="{{obj}}" formControlName="DSYesNo" (change)="DSYesNO(obj)">
{{obj}}
</div>
<div *ngIf='allDSflag'> // allDSflag by default is false.
<div form="form-group">
<label for="allDS"><h3> Data Subject Category: </h3> </label>
<div [ngClass]="{
'has-errors': ((primaryForm.controls.allDS.errors (primaryForm.controls.allDS.dirty || primaryForm.controls.allDS.touched)) ),
'has-success': (!primaryForm.controls.allDS.errors) }">
<div *ngFor="let DScategory of allDataSubjects">
<input type="checkbox"
formControlName="allDS"
name="allDS"
(click)="onOtherDataSubjectClick(DScategory)"
>
{{DScategory.category}}
</div>
<!--Validations-->
<ul class="help-block">
<li *ngIf="primaryForm.controls.allDS.errors?.requiredTrue &&
(primaryForm.controls.allDS.dirty || primaryForm.controls.allDS.touched)">This field is required</li>
</ul>
</div>这里是我检查单选按钮选中值以设置标志的地方。
DSYesNO(value) {
console.log(value);
if (value=="Yes") {
this.allDSflag = true
} else
this.allDSflag = false;
}这是我创建表格的地方:
createForm() {
this.primaryForm = this.formBuilder.group({
DSYesNo: [],
allDS:['', Validators.compose([
Validators.requiredTrue
])],
justifyOtherDS: ['', Validators.compose([
Validators.required
])]
}这是提交按钮,当表单无效时必须禁用:
<input type="submit" class="btn btn-primary" [disabled]="((!primaryForm.valid) && !allDSflag)" value="Submit" />你能帮我理解一下是什么原因导致按钮总是被禁用吗?有人知道吗?
答案#1
如果您想根据其他字段的值来验证字段,可以订阅该字段的 ValueChanges 可观察对象,然后设置或取消验证器。
this.primaryForm.get('DSYesNo')
.valueChanges
.subscribe(value => {
const otherFiled = this.primaryForm .get('otherField');
if(value==='YES'){
otherFiled.enable();
otherFiled.setValidators([Validators.required]);
} else {
otherFiled.disable()
otherFiled.clearValidators();
}
});
要禁用按钮,只需检查表单是否有效
<button type="submit" [disabled]="!primaryForm.valid" class="btn btn-primary ">Submit</button>
