我在 Angular 7 中有一种反应形式,其中包含电子邮件、电话和寻呼机三个字段。我的要求是至少其中一个应该由用户填写,否则我们应该抛出这样的错误“请指定通知之一(电子邮件、短信或寻呼机)。”
我曾尝试编写自定义通知,但它不起作用。你能帮我看看我哪里出错了。
下面是我的 HTML 代码:
<form class="form-horizontal" [formGroup]="editorForm">
<div class="form-group" required>
<label for="emailAdressInput">Email Addresses</label>
<input type="text" id="emailAdressInput" formControlName="emailAdresses">
</div>
<div class="form-group" required>
<label for="phoneNumberInput">Email Addresses</label>
<input type="text" id="phoneNumberInput" formControlName="phoneNumber">
</div>
<div class="form-group" required>
<label for="pagerNumberInput">Email Addresses</label>
<input type="text" id="pagerNumberInput" formControlName="pagerNumber">
</div>
</form>
下面是 component.ts 代码:
this.editorForm = this._formBuilder.group({
displayLabel: ['', Validators.required],
emailAdresses: [''],
phoneNumber: [''],
notification: this._formBuilder.group({
pagerNumber: [''],
phoneNumber: [''],
emailAdresses: ['']
}, this.atLeastOneValidator()),
pagerNumber: [''],
});
public atLeastOneValidator = () => {
return (controlGroup) => {
let controls = controlGroup.controls;
if ( controls ) {
let theOne = Object.keys(controls).find(key=> controls[key].value!=='');
if ( !theOne ) {
return {
atLeastOneRequired : {
text : 'At least one should be selected'
}
}
}
}
return null;
};
};