Here is some potentially helpful code:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { of } from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
form: FormGroup;
orders = [];
marked = false;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
orders: new FormArray([], minSelectedCheckboxes(1))
});
// async orders
of(this.getOrders()).subscribe(orders => {
this.orders = orders;
this.addCheckboxes();
});
// synchronous orders
// this.orders = this.getOrders();
// this.addCheckboxes();
}
private addCheckboxes() {
this.orders.map((o, i) => {
const control = new FormControl(i === 0); // if first item set to true, else false
(this.form.controls.orders as FormArray).push(control);
});
}
getOrders() {
return [
{ id: 100, name: 'order 1', text1: 'select', text2: 'selected' },
{ id: 200, name: 'order 2', text1: 'select', text2: 'selected' },
{ id: 300, name: 'order 3', text1: 'select', text2: 'selected' },
{ id: 400, name: 'order 4', text1: 'select', text2: 'selected' }
];
}
toggleVisibility(e, i) {
console.log(e,i);
console.log(this.orders[i]);
console.log(this.form.controls.orders['controls'].value);
if(this.form.controls.orders['controls'][i].value)
{
this.orders[i].text1 = 'justSelected';
}else{
this.orders[i].text1 = 'UnSelected';
}
console.log(this.form.controls.orders['controls']);
console.log(i);
}
}
function minSelectedCheckboxes(min = 1) {
const validator: ValidatorFn = (formArray: FormArray) => {
const totalSelected = formArray.controls
.map(control => control.value)
.reduce((prev, next) => next ? prev + next : prev, 0);
return totalSelected >= min ? null : { required: true };
};
return validator;
}
Update on the HTML part:
<hello name="{{ name }}"></hello>
<form [formGroup]="form" (ngSubmit)="submit()">
<label formArrayName="orders" *ngFor="let order of form.controls.orders.controls; let i = index">
<input type="checkbox" [formControlName]="i"
(change)="toggleVisibility($event, i)">
<span >
{{orders[i].text1}}
</span>
</label>
<br>
<button [disabled]="!form.valid">submit</button>
</form>