I am trying to verify if a name is present in the database. If so, I want to mark it as invalid and inform to the user this occurrence.
Besides this, I'm looking for the best approach to do this: template driven forms or reactive forms.
Note that I'm using multiple forms like the examples in https://material.angular.io.
Here's my current code:
HTML:
<mat-horizontal-stepper [@.disabled]="true" #stepper>
<mat-step label="Example" [stepControl]="nameForm">
<form [formGroup]="nameForm">
<mat-form-field>
<mat-label>NAME</mat-label>
<input matInput placeholder="Input name" formControlName="name">
</mat-form-field>
<button
matTooltip="Verify name in data base"
(click)="validateName()" <<<< LOOK, HERE IS THE POINT
[disabled]="!loading">Validate Name
<i class="ml-2 fa fa-refresh fa-spin" *ngIf="!loading"></i>
</button>
<div>
<button mat-button matStepperNext>Next</button>
</div>
</form>
</mat-step>
<mat-step label="Endereço" [stepControl]="enderecoForm">
<form [formGroup]="nameForm2">
<mat-form-field>
...
</mat-form-field>
</form>
</mat-step>
... more steps with one form inside of each one
TS:
export class SomeComponent {
constructor(private readonly _formBuilder: FormBuilder) {}
ngOnInit(): void {
this.nameForm = this._formBuilder.group(
{
name: ['', Validators.required],
},
{ validator: this.validateName },
); // AND HERE LOOK
this.nameForm2 = this._formBuilder.group({
name2: ['', Validators.required],
// ... more forms and controls validators with reactive forms
});
}
validateName(fb: FormGroup) {
const nameCtrl = fb.get('name');
// method verifyName return the name from database if exists
const name = this.nameService.verifyName(nameCtrl);
if (nameCtrl.errors == null || 'exists' in nameCtrl.errors) {
if (name == null) {
nameCtrl.setErrors(null);
} else {
nameCtrl.setErrors({ exists: true });
}
}
}
}
confirmSenhaCtrl? Do you want to validate only after button click? Could you post at least the signature of thenameServive.verifyNamefunction?