【问题标题】:Typescript: iterate through checkbox (made by ngfor) and print value of each checkbox打字稿:遍历复选框(由ngfor制作)并打印每个复选框的值
【发布时间】:2020-07-30 04:37:42
【问题描述】:

我想从 ngfor 生成的每个复选框中获取价值 (console.log(somevalue)) 。我的表单显示正常。

代码如下:

<form>
  <div class="form-group row" *ngFor="let firstColumn of mapMenusFirstColumn; index as i;">
    <label class="col-4">{{firstColumn}}</label>
    <div class="col-8">
      <div class="custom-control custom-checkbox custom-control-inline"
        *ngFor="let secondColumn of this.getSecondColumn(this.mapMenu,firstColumn); index as j;">
        
        <input name="checkbox{{i}}" id="checkbox{{i+'_'+j}}" type="checkbox" class="custom-control-input"
          value={{secondColumn}}>
        <label for="checkbox{{i+'_'+j}}" class="custom-control-label">{{secondColumn}}</label>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <div class="offset-4 col-8">
      <button name="submit" type="submit" class="btn btn-primary">Submit</button>
    </div>
  </div>
</form>

这里是设计:

我需要遍历我的所有复选框和console.log() 每个复选框的值。请帮帮我

(请注意:查看我如何生成 Id 和 Name - 就像:

当名字 1 的 id 是 1_1 , 1_2 ..

当名字 2 的 id 是 2_1, 2_2, 2_3, ...

我应该为此更改我的 id 和 name 实现吗?如果有,请告诉我。)

【问题讨论】:

    标签: javascript angular typescript checkbox


    【解决方案1】:

    一个可能的解决方案是使用响应式表单。首先根据数组中的第一列和第二列在组件中创建一个 FormGroup,如下所示:

     buildReactiveForm() {
        this.form = new FormGroup({});
        this.mapMenusFirstColumn.forEach((firstColumnItem, firstIndex) => {
          this.getSecondColumn(this.mapMenu, firstColumnItem).forEach(
            (secondColumnItem, secondIndex) => {
              this.form.addControl(
                "checkbox" + firstIndex + "_" + secondIndex,
                new FormControl(false)
              );
            }
          );
        });
      }
    

    并在您的 HTML 文件中为指定表单控件名称的标签添加另一个属性

    <input name="checkbox{{i}}" id="checkbox{{i+'_'+j}}" formControlName="checkbox{{i+'_'+j}}" type="checkbox" class="custom-control-input">
    

    最后,您可以通过简单地记录表单的值来记录复选框的值

    console.log(this.form.value)
    

    这将有以下输出

    Stackblitz:https://stackblitz.com/edit/questions63098875?file=src/app/app.component.ts

    【讨论】:

    • 你的 stackblitz 令人印象深刻。它非常接近我的代码。您正在“显示页面之前”生成所有框空白。我也想要那个。我还想要一个额外的东西,那就是。让我们留下 2 个复选框中的 10 个将在“显示页面之前”从打字稿中检查。 [我将通过使用数组检查复选框值来确定它。我重复一遍,我必须在从打字稿“加载页面之前”执行此操作。如果您有时间,请考虑更新您的 stackblitz。提前致谢。也非常感谢您的回答。
    • 在显示页面之前我不太明白您的意思。如果您需要为某些复选框设置值,只需创建一个方法并调用 this.form.get("checkbox" + 1 + "_" + 1).setValue(true);对于您要检查的任何复选框。初始化表单后调用该方法。更新堆栈闪电战
    猜你喜欢
    • 2015-02-20
    • 1970-01-01
    • 2018-11-12
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 2017-04-13
    相关资源
    最近更新 更多