1
votes

I have an issue with Angular 4 reactive forms.

My application is a training project. It has a Backend in SpringBoot, mySql database, and forms in Angular4.

This app have to Add doctors to Database, but also have to validate: the license number has to be uniqe. I am using Reactive Forms (not template driven).

I tried to solve my problem with function:

    import { AbstractControl } from "@angular/forms";



export function  ControlLicenseNumber(c: AbstractControl):  string | null {
  const formGroup = c.parent.controls;
  return Object.keys(formGroup).find(license_number => c === formGroup[license_number])  || null;
 }

but i don't know how to inject it to my formControl:

   constructor(private doctorsService: DoctorsService,
              private location: Location,
              private fb: FormBuilder) {
                this.rForm = new FormGroup({ 
                'name': new FormControl('', Validators.required),
                'surname': new FormControl('', Validators.required),
                'phone': new FormControl('', Validators.required),
                'nationality': new FormControl('', Validators.required),
                'email': new FormControl('', Validators.email),
                'license_number': new FormControl('', [Validators.required, ControlLicenseNumber])})
                 }

Hope you'll help me guys. Greetings

1
Where do would you like to place this validator? I see no license_number form control in your form? Also, why are you setting objects to your form controls? :)AT82
Ok, I've eddited my code :)Bartłomiej Matyjaszczyk
I'm just learning and these objects are from some tutorial... so if it is wrong practice I deleted it as you told.Bartłomiej Matyjaszczyk
Looks better now :) Yes, form control should take only primitive value.(nested) formgroups are used for objects.AT82
Thank you for that advice. What I should do next to validate license_number? I went throught the whole internet :/Bartłomiej Matyjaszczyk

1 Answers

0
votes

Try like this:-

constructor(private doctorsService: DoctorsService,
          private location: Location,
          private fb: FormBuilder) {
            this.rForm = this.fb.group({({ 
              name           : ['', [Validators.required]],
              surname        : ['', [Validators.required]],
              phone          : ['', [Validators.required],
              nationality    : ['',[Validators.required]],
              email          : ['', Validators.email],
              license_number : ['', [Validators.required]
              },
             {
                validator: this.ControlLicenseNumber
           });
}

ControlLicenseNumber(c: AbstractControl){
  const value = c.get('license_number').value;
  return Object.keys(value).find(license_number => c === 
  value)  || null;
}