Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 : How to assign array of string into checkbox in reactive forms

I am trying display checkboxes for my user roles:

For eg. I have two user roles : 1.Admin 2.Employee

I have an array of roles in userObject:

user={
    "name":"Bhushan",
    "email":"[email protected]",
    "roles":['Admin','Employee']
}

I want to use reactive form to populate this model into form. I want to populate the roles array into read-only checkboxes i.e. when form loads, user can edit name & email but checkboxes will show admin toggeled if user has admin role or untoggled if he is not an admin. same can be said for employee role.

So far I have tried following:

<form [formGroup]="userForm" (ngSubmit)="onSubmit()" novalidate>
  <div style="margin-bottom: 1em">
    <button type="submit" [disabled]="userForm.pristine" class="btn btn-success">Save</button> &nbsp;
    <button type="reset" (click)="revert()" [disabled]="userForm.pristine" class="btn btn-danger">Revert</button>
  </div>
  <div class="form-group">
    <label class="center-block">Name:
        <input class="form-control" formControlName="name">
    </label>
  </div>
  <div class="form-group">
    <label class="center-block">Email:
        <input class="form-control" formControlName="email">
    </label>
  </div>
  <div class="form-group" *ngFor="let role of roles;let i=index">
    <label>
        // I tried this, but it doesn't work
        <!--<input type="checkbox" [name]="role" [(ngModel)]="role">-->
       {{role}}
    </label>
  </div>
</form>

<p>userForm value: {{ userForm.value | json}}</p>`

Any Inputs?

like image 811
Bhushan Gadekar Avatar asked Jun 27 '17 08:06

Bhushan Gadekar


1 Answers

Perhaps do something like the following. Build your form, and stick the roles in a form array:

this.userForm = this.fb.group({
  name: [this.user.name],
  roles: this.fb.array(this.user.roles || [])
});

// OPTIONAL: put the different controls in variables
this.nameCtrl = this.userForm.controls.name;
this.rolesCtrl = this.userForm.controls.roles.controls;

and the roles array you are iterating in the template could look like this:

roles = ['Admin', 'Employee','Some role 1', 'Some role 2']

and in your iteration just compare and set the role in roles array as checked in case it matches a value in the form array. Use safe navigation operator, as we know that the roles array is probably longer that the form array, so that an error won't be thrown trying to read an index that doesn't exist:

<div class="form-group" *ngFor="let role of roles;let i=index">
  <input [checked]="role == rolesCtrl[i]?.value" 
     [disabled]="true" type="checkbox">{{role}}
</div>

DEMO

like image 186
AT82 Avatar answered Oct 15 '22 15:10

AT82