【问题标题】:Angular 8 - How to capture checkbox value on submit in the form of array of objectAngular 8 - 如何以对象数组的形式在提交时捕获复选框值
【发布时间】:2019-11-17 23:29:25
【问题描述】:

我在父子结构中有一些复选框,我需要根据输出格式中的选择来捕获/控制复选框的值(已经在代码中作为硬编码格式的输出给出)。下面是代码

home.component.html

<p>home works!</p><div class="col-md-3" id="leftNavBar">
    <ul>
        <li class="parentNav">parent1</li>
        <li class="childData">
            <ul>
                <li>child11<span class="pull-right"> <input checked type="checkbox"></span></li>
                <li>child12<span class="pull-right"> <input checked type="checkbox"></span></li>
            </ul>
        </li>
    </ul>

    <ul>
        <li class="parentNav">parent2</li>
        <li class="childData">
            <ul>
                <li>child2<span class="pull-right"> <input checked type="checkbox"></span></li>
            </ul>
        </li>
    </ul>

    <ul>
        <li class="parentNav">parent3</li>
        <li class="childData">
            <ul>
                <li>child3<span class="pull-right"> <input type="checkbox"></span></li>
            </ul>
        </li>
    </ul>

    <div><button (click)="submit()" type="submit">submit</button></div>

</div>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  getListData: any;
  constructor(private commonserviceService: CommonserviceService) { }

  ngOnInit() {
      this.getHeroes();
  }
  submit(){
      alert('hi');
      console.log([{"name":"parent1","value":["child11","child12"]},{"name":"parent2","value":["child2"]}]);
  }
getHeroes(){
   this.commonserviceService.getData().subscribe(getListData =>{
          this.getListData = getListData;
          console.log(this.getListData);
      },
      (error) => {
      alert('No data');
      }
  );
}
}

【问题讨论】:

    标签: html angular


    【解决方案1】:

    真的,Uiappdeveloper,你的问题有点困惑,所以我必须假设你有一个类似的模型

    model=[{"name":"parent1","value":["child11","child12"]},
           {"name":"parent2","value":["child2"]},
           {"name":"parent3","value":["child31","child32"]}]
    

    还有一个数据,例如

    data = [
        { name: "parent1", value: ["child11", "child12"] },
        { name: "parent2", value: ["child2"] }
      ];
    

    并且您想显示一个复选框列表,如示例中所示。我们首先需要的是一个函数,它接收“数据”并基于模型和数据创建 FormArray 的 FormArray

      getFormArray(value: any[]) {
        return new FormArray(
          this.model.map((x, index) => {
            const data = value ? value.find(d => x.name == d.name) : null;
    
            return new FormArray(
              x.value.map(
                c => new FormControl(data ? data.value.indexOf(c) >= 0 : false)
              )
            );
          })
        );
      }
    

    还有显示“模型”和“数据”的 .html

    <div class="col-md-3" id="leftNavBar">
      <form [formGroup]="formArray" (submit)="submit(formArray)">
      <ul *ngFor="let array of formArray.controls;let i=index">
        <li class="parentNav">{{model[i].name}}</li>
        <li class="childData">
          <ul *ngFor="let control of array.controls;let j=index">
            <li>{{model[i].value[j]}}
              <input type="checkbox" [formControl]="control">
    
            </li>
          </ul>
        </li>
      </ul>
        <div><button  type="submit">submit</button></div>
    </form>
    

    看到formArray.value只是一个数组,其值为true或false,看看我们如何使用变量over我们迭代“array”和“control”来写[formControl]="control"。

    嗯,我们的formArray.value可以在一瞬间像

    [ [ true, true ], [ true ], [ false, false ] ]
    

    我们想要的对象如何变换?为此我们可以使用提交功能,有些像

      submit(formArray: FormArray) {
        const result = this.model.map((x: any, index) => {
          return {
            name: x.name,
            value: x.value.filter((v, j) => formArray.at(index).value[j])
          };
        });
        this.result = result.filter(x => x.value.length > 0);
        //in this.result we has the object we want
      }
    

    您可以在stackblitz 中查看实际操作

    【讨论】:

    • 感谢您对复选框的回答,它工作正常,但如果我使用 html,则对于单选框,
    • {{model[i].value[j]}}
    • ..预期输出不正确
  • 单选按钮是唯一的 FormControl,而不是 FormArray。你需要问你:我需要什么数据?我有什么数据?我有什么模型?我无法想象你的数据。在我的代码中,我使用 model 来使用 map 创建一个 FormArray。通常,您将拥有一个模型并创建一个以 .html 显示的 FormGroup
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签