I'm looking for the best way to submit multiple values through a single checkbox. The values are are being saved in a service.
Using the attribute syntax I can bind to an additional data-* property. Is there a way to consolidate the the values of the custom data-* and value attributes to send together on 'submission' or should this be approached differently using the getAttribute() method?
Template
<form [formGroup]="myForm" novalidate>
<template ngFor let-stock [ngForOf]="availableStock">
<p><label><input type="radio" formControlName="size" [value]="stock.size" [attr.data-stock-sku]="stock.sku" [id]="stock.size">{{ stock.size }}</label></p>
</template>
<p><button type="submit" (click)="onSubmit()">Submit</button></p>
</form>
Component
@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.component.html',
styleUrls: ['./reactive-form.component.css']
})
export class ReactiveFormComponent implements OnInit {
public myForm: FormGroup;
public availableStock: Array<{"size": string, "sku": string}> = [{"size": "36", "sku": "5409756"}, {"size": "38", "sku": "5409750"},{"size": "40", "sku": "5409754"}];
constructor(private _formBuilder: FormBuilder) {
this.createForm();
}
createForm(){
this.myForm = this._formBuilder.group({
size: [ null , Validators.required ]
});
}
ngOnInit() {
}
onSubmit() {
if(this.myForm.valid) {
// submit form eg this._formService.saveFormValues(this.myForm.value);
} else {
// display errors
}
}
}
EDIT: For clarity, I would like to submit/save multiple values which are assigned to a single checkbox. These are the values assigned to the 'value' attribute and the data-stock-sku/attr.data-stock-sku attribute in the HTML. However on submission Angular only sends through the value assigned to the 'value' attribute by default.
checkboxis ticked?stockobject (and you do not need to display them in your html. Then, you can subscribe to your checkbox value, and decide what to do with yourstockform.