使用 Angular 4,我有一个带有复选框的反应式表单。必须至少选中其中一个复选框才能提交表单。
我创建了一个自定义验证,它似乎返回正确的值,但表单始终无效。但是,当我检查表单控件是否有错误时,我得到错误。
这是具有相同行为的示例代码:
@Component({
selector: 'my-app',
providers: [FormBuilder],
template: `
<div>
Checkbox values: {{alertForm.value | json}}
<mark> Is Form Valid: {{alertForm.valid}} </mark> <-- WHY IS FORM VALID ALWAYS FALSE?
Does Fields have error: {{alertForm.get('fields').hasError('checkboxSelected')}}
</div>
<form [formGroup]="alertForm">
<fieldset class="form-group" formGroupName="fields">
<legend class="col-md-4"> Fields</legend>
<div class="col-md-8 checkbox column-2">
<label *ngFor="let type of types.controls; let i=index">
<input name="fieldsAdd" type="checkbox" [formControl]="type" />
{{fields[i].name}}
</label>
</div>
</fieldset>
</form>
`
})
export class App implements OnInit {
alertForm: FormGroup;
fields …Run Code Online (Sandbox Code Playgroud)