mardi 27 juin 2017

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":"bhushan@yaho.com",
    "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">-->
       
    </label>
  </div>
</form>

<p>userForm value: </p>`

Any Inputs?




Aucun commentaire:

Enregistrer un commentaire