dimanche 27 janvier 2019

Angular 6 Reactive Form - how to add dynamic checkboxe to 3 columns

I am creating dynamic checkbox in a reactive form. For the sake of demo, I have some static data but eventually will use service. Since there can be long list of items for checkbox, I want to display them in 3 columns. I tried changing the css, but I have idea how to achieve this. Template:

<form [formGroup]="ReportsForm" (ngSubmit)="submit()">

    <!--Check boxes-->
    <div class="cb-wrapper" [ngClass]="{'cb-vertical':!tmp}">
        <label formArrayName="orders"
               *ngFor="let order of ReportsForm.controls.orders.controls; let i = index">
            <input type="checkbox" [formControlName]="i">
            
        </label>
    </div>
    <br />

    <div *ngIf="!ReportsForm.valid">At least one order must be selected</div>
    <button>submit</button>
</form>

Code in component

import { Component } from '@angular/core';
import { ReactiveFormsModule, FormBuilder, FormGroup, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { asEnumerable } from 'linq-es2015';

@Component({
    selector: 'app-report',
    templateUrl: './report.component.html',
    styleUrls: ['./report.component.scss']
})
export class ReportComponent {

    ReportsForm: FormGroup;
    orders = [
        { id: 1, name: 'chk 1' },
        { id: 2, name: 'chk 2' },
        { id: 3, name: 'chk 3' },
        { id: 4, name: 'chk 4' },
        { id: 5, name: 'chk 5' },
        { id: 6, name: 'chk 6' },
        { id: 7, name: 'chk 7' },
        { id: 8, name: 'chk 8' },
        { id: 9, name: 'chk 9' },
        { id: 10, name: 'chk 10' },
        { id: 11, name: 'chk 11' },
        { id: 12, name: 'chk 12' },
        { id: 13, name: 'chk 13' },
        { id: 14, name: 'chk 14' },
        { id: 15, name: 'chk 15' },
        { id: 16, name: 'chk 16' },
        { id: 17, name: 'chk 17' },
        { id: 18, name: 'chk 18' }
    ];

    tmp: boolean = false;
    constructor(private formBuilder: FormBuilder) {
        // Create a new array with a form control for each order. All selected to true by default
        const controls = this.orders.map(c => new FormControl(true));
        this.ReportsForm = this.formBuilder.group({
            orders: new FormArray(controls)
        });
    } 

    ngOnInit() {
    }

    submit() {
        const selectedOrderIds = this.ReportsForm.value.orders
            .map((v, i) => v ? this.orders[i].id : null)
            .filter(v => v !== null);
        console.log(selectedOrderIds);
    }
}




Aucun commentaire:

Enregistrer un commentaire