Как я могу выполнить проверку при запуске и построении формы.
У меня есть следующий код:
// lef out imports
const noopValidatorFn: ValidatorFn = control => null;
@Component({
})
export class ProfileComponent implements OnChanges, OnInit {
// left out User variable.
get functionGroupsForm(): FormArray {
return this.accountForm.get('functionGroups') as FormArray;
}
buttonOptions = buttonOptions('Save');
accountForm: FormGroup;
requiredField = 'Field is required';
countries: string[] = ['Nederland', 'België', 'Duitsland'];
formErrors = {
firstName: '',
phoneNumber: '',
cellPhoneNumber: '',
};
validationMessages: any = {
firstName: { required: this.requiredField },
phoneNumber: { required: this.requiredField },
cellPhoneNumber: { required: 'Vul een mobiel of vast telefoonnummer in' }};
constructor(private readonly formBuilder: FormBuilder) {}
ngOnInit(): void {
this.role = this.authenticationService.getRole();
this.generatePhoneNumberValidationMessage();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.user) {
if (this.user) {
this.buildForm();
this.accountFormChange();
setTimeout(() => {
this.accountForm.patchValue(this.accountForm.value);
});
}
}
}
buildForm(): void {
this.accountForm = this.formBuilder.group({
firstName: [this.user.firstName, Validators.required],
phoneNumber: [this.user.phoneNumber, Validators.required],
cellPhoneNumber: [this.user.cellPhoneNumber, Validators.required],
});
// Object.keys(this.accountForm.controls).forEach(field => {
// const control = this.accountForm.get(field);
// control.updateValueAndValidity();
// });
// this.onValueChanged();
}
accountFormChange(): void {
this.accountForm.valueChanges.subscribe(() => {
if (this.role !== Role.Employee) {
const phoneNumber = this.accountForm.get('phoneNumber');
const cellPhoneNumber = this.accountForm.get('cellPhoneNumber');
if (!phoneNumber.value && !cellPhoneNumber.value) {
phoneNumber.setValidators([Validators.required]);
cellPhoneNumber.setValidators([Validators.required]);
} else {
if (phoneNumber.value) {
phoneNumber.setValidators([Validators.required]);
cellPhoneNumber.clearValidators();
}
if (cellPhoneNumber.value) {
cellPhoneNumber.setValidators([Validators.required]);
phoneNumber.clearValidators();
}
}
phoneNumber.updateValueAndValidity({ emitEvent: false });
cellPhoneNumber.updateValueAndValidity({ emitEvent: false });
}
this.buttonOptions.disabled = !this.accountForm.valid;
this.onValueChanged();
});
}
onValueChanged(): void {
const form = this.accountForm;
for (const field in this.formErrors) {
if (this.formErrors.hasOwnProperty(field)) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
if (control.errors.hasOwnProperty(key)) {
this.formErrors[field] += `${messages[key]} `;
}
}
}
}
}
}
}
Я пробовал несколько подходов, например patchValue setTimeout (),Кажется, ничего не работает.
PhoneNumber необходим для правильности формы, но он должен показывать сообщение об ошибке немедленно на ngOnChanges, потому что значение пусто.Теперь он не показывает никаких сообщений об ошибках, но кнопка отключена (потому что valueChanges еще не запущен).
Как мне получить этот результат?
РЕДАКТИРОВАТЬ: забыли включитьмой HTML
<div class="tab-content" *ngIf="user">
<form [formGroup]="accountForm">
<div class="form-block">
<div class="form-row">
<mat-form-field>
<input matInput placeholder="Firstname" formControlName="firstName" />
<mat-error *ngIf="formErrors.firstName">
{{ formErrors.firstName }}
</mat-error>
</mat-form-field>
</div>
<div class="form-row">
<mat-form-field>
<input matInput placeholder="Mobiel" type="number" formControlName="cellPhoneNumber" />
<mat-error *ngIf="formErrors.cellPhoneNumber">
{{ formErrors.cellPhoneNumber }}
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Telefoonnummer" type="number" formControlName="phoneNumber" />
<mat-error *ngIf="formErrors.phoneNumber">
{{ formErrors.phoneNumber }}
</mat-error>
</mat-form-field>
</div>
<div class="actions">
<mat-spinner-button (btnClick)="editAccountInformation()" [options]="buttonOptions" class="mat-spinner-color">
</mat-spinner-button>
</div>
</div>
</form>
</div>