简体   繁体   English

在 UI 中使用 Angular 反应式 forms 显示选中的复选框

[英]In UI present checked checkboxes using Angular reactive forms

I have a form that sends the correct data to my api/forms array on "save".我有一个表单,可以在“保存”时将正确的数据发送到我的 api/forms 数组。 There is an array of checkboxes that the user can select.用户可以使用一系列复选框 select。 Once selected I want to give a summary of the values selected.选择后,我想给出所选值的摘要。 I can present this after form save as the values will be on the reactive forms array, however I want to pick up the value for presentation purposes before save/form submission.我可以在表单保存后呈现此值,因为这些值将位于反应式 forms 数组上,但是我想在保存/表单提交之前获取用于演示目的的值。 StackBlitz - https://stackblitz.com/edit/angular-fgupp3 StackBlitz - https://stackblitz.com/edit/angular-fgupp3

I've nearly accomplished this however the first checkbox brings back a true/false value whereas the rest of the checkboxes return the desired value我几乎完成了这个但是第一个复选框带回一个真/假值,而复选框的 rest 返回所需的值

component.html组件.html

<form [formGroup]="form" (ngSubmit)="onSubmit('formSubmit')" novalidate>

    <div class="row">
      <div class="col-md-8">{{form.value.selection}}</div> <!--present selected values here -->
        <div class="col-md-8">
            <input type="text" formControlName="title" class="form-control" placeholder="Title">
        </div>

        <div class="col-md-6">
            <label formArrayName="selection" *ngFor="let order of form.controls.selection.controls; let i = index">
                <input (change)="onChange(i, $event)" type="checkbox" [formControlName]="i">
                {{ordersData[i].name}}
            </label>
        </div>
    </div>
    <div class="form-group text-center">
        <button class="btn btn-success btn-info" (click)="goToNext(Work)"> Next </button>
    </div>

</form>

component.ts组件.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Personal } from '../data/formData.model';
import { FormDataService } from '../data/formData.service';
import { of } from 'rxjs';
import { FormGroup, FormBuilder, ValidatorFn, FormArray, FormControl } from '@angular/forms';

@Component({
    selector: 'mt-wizard-personal',
    templateUrl: './personal.component.html',
})

export class PersonalComponent implements OnInit {
    personal: Personal;
    form: FormGroup;
    ordersData = [];
    selectedItems: any[] = [];

    constructor(private formBuilder: FormBuilder, private router: Router, private formDataService: FormDataService) {
    }

    ngOnInit() {
        this.personal = this.formDataService.getPersonal();
        this.form = this.createEntry(this.formBuilder);

        // synchronous orders
        // this.ordersData = this.getOrders();
        // this.addCheckboxes();

        of(this.getOrders()).subscribe(selection => {
            this.ordersData = selection;
            this.addCheckboxes();
        });
    }

    createEntry(formBuilder: FormBuilder) {
        return this.formBuilder.group({
            title: this.personal.title,
            creationDate: this.personal.creationDate,
            //selection: new FormArray([], minSelectedCheckboxes(1))
            selection: new FormArray([])
        });
    }

    private addCheckboxes() {
        this.ordersData.forEach((o, i) => {
            const control = new FormControl; // if first item set to true, else false
            (this.form.controls.selection as FormArray).push(control);
        });
    }


    getOrders() {
        return [
            { id: 100, name: 'order 1' },
            { id: 200, name: 'order 2' },
            { id: 300, name: 'order 3' },
            { id: 400, name: 'order 4' }
        ];
    }

    onChange(i: boolean) {
        console.log(i);
        if (i) {
            const selectedOrderIds = this.form.value.selection
                .map((v, i) => v ? this.ordersData[i].id : null)
                .filter(v => v !== null);

            return this.form.value.selection = selectedOrderIds;
        }
    }

    save(form: any): boolean {
        const selectedOrderIds = this.form.value.selection
            .map((v, i) => v ? this.ordersData[i].id : null)
            .filter(v => v !== null);
        console.log(selectedOrderIds);
        this.form.value.selection = selectedOrderIds;
        const data: Personal = Object.assign({}, this.form.value);
        this.formDataService.setPersonal(data);

        return true;
    }

    goToNext(form: any) {
        if (this.save(form)) {
            // Navigate to the work page
            this.router.navigate(['/work']);
        }
    }

}

The issue about the first value marked as true instead of 100 can be solved change the if in onChange function line 76 if (i || i===0) :关于第一个值标记为true而不是100的问题可以解决更改onChange function 第 76 行if (i || i===0)

   onChange(i: boolean) {
        if (i || i===0) {
            const selectedOrderIds = this.form.value.selection
                .map((v, i) => v ? this.ordersData[i].id : null)
                .filter(v => v !== null);
            return this.form.value.selection = selectedOrderIds;
        }
    }

Unfortunately in javascript number = 0; if(number)不幸的是,在 javascript number = 0; if(number) number = 0; if(number) it is a falsy expression. number = 0; if(number)它是一个虚假的表达式。 Also OnInit method is a little messy, instead having a method getOrders() i will use a variable in component someting like this: OnInit方法也有点混乱,取而代之的是方法getOrders()我将在组件中使用一个变量,如下所示:

orders = [
  { id: 100, name: 'order 1' },
  { id: 200, name: 'order 2' },
  { id: 300, name: 'order 3' },
  { id: 400, name: 'order 4' }
]

that can be use both in component.ts and.html and i will simplified 'OnInit` like this:可以在 component.ts 和.html 中使用,我将像这样简化“OnInit”:

ngOnInit() {
    this.personal = this.formDataService.getPersonal();
    const ordersArray = new FormArray([]);
    this.orders.forEach(order => {
      ordersArray.push(new FormControl);
    });

    this.form = this.formBuilder.group({
        title: this.personal.title,
        creationDate: this.personal.creationDate,
        selection: ordersArray
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM