Issue
i have a form created using formbuilder. I created a set of checkboxes using an array containing an id and a name for each value. I have it returning the name of the value checked by the user but i also need the id. Is there an efficient way of returning both the name and the id together rather than doing this separately? as i need the id with the name to manipulate the data later. Thanks in advance.
TS code
checkboxGroup: FormGroup;
public colors = [
{id:-4, name:'red'},
{id:-3, name:'blue'},
{id:-2, name:'green'},
{id:-1, name:'yellow' }
];
// set the initial value of the checkboxes to false
this.checkboxGroup = this.formBuilder.group({
colors: this.formBuilder.array(this.colors.map(x => false))
});
// return values marked as true (checked)
const checkboxControl = (this.checkboxGroup.controls. colors as FormArray);
this.subscription = checkboxControl.valueChanges.subscribe(checkbox => {
checkboxControl.setValue(checkboxControl.value.map((value, i) => value ? this. colors[i].name : false),
{ emitEvent: false }
)})
HTML code
<form class="checkbox" [formGroup]="checkboxGroup">
<ion-card-subtitle>
<ion-label class="title">
colors
</ion-label>
</ion-card-subtitle>
<ion-card-content>
<ng-container *ngFor="let checkbox of colors; let i = index" formArrayName="colors">
<!--iterate over valence array-->
<input type="checkbox" class="checkbox inline"[formControlName]="i"/>{{checkbox.name}}
<br/>
</ng-container>
<!-- <button (click)="submit()">Submit</button> -->
</ion-card-content>
</form>
Solution
Your extended model:
public colors = [
{id:-4, name:'red', checked: boolean},
{id:-3, name:'blue', checked: boolean},
{id:-2, name:'green', checked: boolean},
{id:-1, name:'yellow', checked: boolean}
];
Add the change()
method to your checkbox-tag.
<ng-container *ngFor="let checkbox of colors; let i = index"
formArrayName="colors">
<!--iterate over valence array-->
<input type="checkbox"
class="checkbox inline"
[formControlName]="i"
[checked]="checkbox.checked"
(change)="onChange(checkbox)"
/>{{checkbox.name}}
<br />
</ng-container>
Add this method to your Typescript file
public onChange(checkbox: any): void {
checkbox.checked = !checkbox.checked;
}
An alternative is to use ngModel
. Then you don't even need the (change)
event. Because the ngModel
-directive directly writes the checked state TRUE/FALSE into the field checked
of the current object.
HTML
<ng-container *ngFor="let checkbox of colors; let i = index"
formArrayName="colors">
<!--iterate over valence array-->
<input type="checkbox"
class="checkbox inline"
[formControlName]="i"
[checked]="checkbox.checked"
[(ngModel)]="checkbox.checked"
/>{{checkbox.name}}
<br />
</ng-container>
In either case you have now the changed state directly written to you object when you click the checkbox and it can be submitted with the form state.
Answered By - Lynx 242
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.