简体   繁体   中英

Angular 7 Register with roles

I want to validate a group checkbox in register form. The checkboxes are roles, 3 roles. The validation is at least one checkbox selected. I have this error: this.controls is undefined. My code:

 ngOnInit() {
      this.roleService.getRoles().subscribe((data: any) => {
        data.forEach(obj => obj.selected = false);
        this.roles = data;
       });

    /************************validators****************************************/

    this.registerForm = this.formBuilder.group({
      name: ['', [Validators.required, Validators.maxLength(20)]],
      surname: ['', [Validators.required, Validators.maxLength(20)]],
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(6)]],
      confirmPassword: ['', Validators.required],
    }, {
      validator: MustMatch('password', 'confirmPassword'),
      roles: new FormArray(this.roles, minSelectedCheckboxes(1))

    });
} 


 export function minSelectedCheckboxes(min = 1) {
   const validator: ValidatorFn = (formArray: FormArray) => {
     const totalSelected = formArray.controls

     .map(control => control.value)
     .reduce((prev, next) => next ? prev + next : prev, 0);

      return totalSelected >= min ? null : { required: true };
   };
    return validator;
  }

HTML

  <div class="col-md-4" *ngFor="let role of roles; let i = index">
      <div class="form-group bmd-form-group form-check">
          <label class="form-check-label">
             <input class="form-check-input" type="checkbox" value="{{ role.id }}" [checked]="role.selected"  (change)="updateSelectedRoles(i)">
            <span class="form-check-sign">
                 <span class="check"></span>
            </span>
            {{ role.name }}
           </label>
       </div>
   </div>

Possible solution

ngOnInit() {

/************************validators****************************************/
this.registerForm = this.formBuilder.group({
  name: ['', [Validators.required, Validators.maxLength(20)]],
  surname: ['', [Validators.required, Validators.maxLength(20)]],
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.minLength(8)]],
  confirmPassword: '',
}, {
  validator: MustMatch('password', 'confirmPassword'),
});

this.roleService.getRoles().subscribe(data => {
  this.roles = data;
  const controls = this.roles.map(c => new FormControl(false));
  this.registerForm.addControl('roles', new FormArray(controls, minSelectedCheckboxes(1)));
});

}

 onSubmit() {

const selectedRoles = this.registerForm.value.roles
.map((v, i) => { return v ? this.roles[i] as Role : null;
})
.filter(v => v !== null);

if (this.user == null) {
  this.user = new User();
}

this.user.role = selectedRoles;

this.user.name = this.registerForm.controls.name.value;
this.user.surname = this.registerForm.controls.surname.value;
this.user.email = this.registerForm.controls.email.value;
this.user.password = this.registerForm.controls.password.value;
}

<div class="col-md-4" *ngFor="let role of registerForm.controls['roles'].controls; let i = index">
   <div class="form-group bmd-form-group form-check">
       <label  formArrayName="roles" class="form-check-label">
            <input class="form-check-input" type="checkbox" value="{{roles[i].id}}" [formControlName]="i">
                {{roles[i].name}}
        </label>
     </div>
  </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM