Statt auf jedem Formcontrol den Validator der Markierung, eine verschachtelte Gruppe für die Telefonnummern machen und den Validator zu dieser Gruppe gelten. In diesem Beispiel werde ich nur den Validator auf das ganze Formular anwenden.
Auch bei der Anwendung von Validatoren müssen wir null
zurückgeben, wenn das Feld gültig ist.
Da Sie auch Winkelmaterial verwenden, müssen Sie eine ErrorStateMatcher
hinzufügen, um mat-errors
anzeigen zu können. mat-errors
werden nur angezeigt, wenn die Validatoren so eingestellt sind, dass sie die Kontrolle bilden, keine Formgroup.
Ihr Code aussehen sollte wie folgt:
createFormGroup() {
this.myForm = this.fb.group({
mobile : new FormControl(''),
homePhone : new FormControl('')
// our custom validator
}, { validator: this.atLeastOnePhoneRequired});
}
atLeastOnePhoneRequired(group : FormGroup) : {[s:string ]: boolean} {
if (group) {
if(group.controls['mobile'].value || group.controls['homePhone'].value) {
return null;
}
}
return {'error': true};
}
Der Fehlerzustand Matcher:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const controlTouched = !!(control && (control.dirty || control.touched));
const controlInvalid = !!(control && control.invalid);
const parentInvalid = !!(control && control.parent && control.parent.invalid && (control.parent.dirty || control.parent.touched));
return (controlTouched && (controlInvalid || parentInvalid));
}
}
, die Sie in der Komponente markiert mit:
matcher = new MyErrorStateMatcher();
und dann markieren zu Ihrer Vorlage in beiden Eingabefeldern. Beachten Sie auch, wie die *ngIf
Prüfungsmeldungen für die Anzeige aussieht:
<mat-form-field>
<input matInput placeholder="Mobile" formControlName="mobile" [errorStateMatcher]="matcher">
<mat-error *ngIf="myForm.hasError('error')">
"Enter either phone number"
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Home Phone" formControlName="homePhone" [errorStateMatcher]="matcher">
<mat-error *ngIf="myForm.hasError('error')">
"Enter either phone number"
</mat-error>
</mat-form-field>
StackBlitz
https://stackoverflow.com/questions/31788681/angular2-validator-which-relies-on-multiple- Formularfelder – Eliseo