我有一个反应性表单,它有一个带有复选框的表和每一行的一些用户输入。我希望这样做,如果用户选中一个复选框,相应的输入需要填写。例如,如果选中了11+,但是相应的用户输入(即价格)没有填写,并且用户试图按下add按钮,那么它就不应该提交表单和表单,而应该提供消息。我不知道如何有条件地应用这个逻辑。
在TS中的表格:
this.addSubjectForm = new FormGroup({
'type' : new FormControl(null, Validators.required),
'subject' : new FormControl(null, Validators.required),
'discount' : new FormControl(null),
'levelDefinition' : new FormGroup({
'11+' : new FormControl(null),
'KS3' : new FormControl(null),
'GCSE' : new FormControl(null),
'A-Level' : new FormControl(null),
'Degree' : new FormControl(null)
})HTML表格/表格:
<form [formGroup]="addSubjectForm" (ngSubmit)="onAddSubject()">
<!-- the first three inputs (type, subject and discount) are not included here to reduce the amount of code shown in the question -->
<div formGroupName="levelDefinition">
<table class="table table-bordered table-condensed table-hover">
<thead>
<tr>
<th class="text-center">
<input type="checkbox" name="all"
(change)="isSelected = !isSelected" />
</th>
<th>Level</th>
<th>Price</th>
<th>Discounts</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let level of levels ; let i = index">
<td class="text-center" >
<input type="checkbox"
value="{{level.id}}"
appHighlightOnCheck
formControlName="{{level}}"
[checked]="isSelected" />
</td>
<td class="text-center">{{ level }}</td>
<td>
<input
type="text"
class="form-control">
</td>
<td>
<input
type="text"
class="form-control">
</td>
</tr>
</tbody>
</table>
</div>
</form>
<button class="btn btn-primary" type="submit">Add</button>发布于 2018-04-05 22:47:49
这样做的方法是使用跨字段自定义验证器。您需要使用表单组(在ts和html中)嵌套2个表单控件。然后,您需要构建一个自定义验证器,并将其附加到这个formGroup上。
https://stackoverflow.com/questions/49682414
复制相似问题