I'm trying to create a form where I can add checkboxes
dynamically based on the data received from API.
I successfully received the data in JSON format as below
[
{
"code": "TicketTypeRead",
"name": "Read Ticket Types"
},
{
"code": "BatchRead",
"name": "Read Batches"
},
{
"code": "BatchWrite",
"name": "Create Batches"
},
{
"code": "TopupWrite",
"name": "Add Topups"
},
{
"code": "ValidationWrite",
"name": "Can Do Validation"
}
]
Based on this data I want to add checkboxes on the page using Reactive form approach in Angular. What I tried is I create a FormGroup
like below
constructor(private router: Router,
private fb: FormBuilder,
private route: ActivatedRoute,
private _deviceService: DeviceService) { }
this.deviceForm = this.fb.group({
apiKey: '',
chariotId: [null, numberOnly],
deviceUID: ['', Validators.required],
//enabled:true,
name: ['', Validators.required],
bearer: ['', Validators.required],
sotiId: null,
permissions: this.fb.array([])
})
and when I received the data from service, tried to add it in permissions FormArray as below. But this doesn't show anything on the page.
onPermissionsRetrieved(permissions: IPermissions[]):void
{
var items = this.deviceForm.get('permissions') as FormArray;
for (let permission of permissions)
{
items.push(this.buildPermission(permission.code, permission.selected));
}
}
I can see the FormGroup value which is:
value:{ "apiKey": "",
"chariotId": null,
"deviceUID": "",
"name": "",
"bearer": "",
"sotiId": null,
"permissions": [ { "code": "TicketTypeRead", "selected": null },
{ "code": "BatchRead", "selected": null },
{ "code": "BatchWrite", "selected": null },
{ "code": "TopupWrite", "selected": null },
{ "code": "ValidationWrite", "selected": null } ] }
Any suggestions what is missing? I'm using Angular 4.4.4
EDIT: template code looks like this
<div class="form-group">
<label class="control-label">Permissions</label>
<div formArrayName="permissions" *ngFor="let permission of permissions.controls; let i=index">
<input formControlName="code" type="checkbox" id="{{permission.code}}" />
<label>{{permission.name}}</label>
</div>
</div>