【问题标题】:How do we set dynamic checkboxes to checked based on the value from the database in angular reactive forms?我们如何根据角度反应形式的数据库中的值将动态复选框设置为检查?
【发布时间】:2021-02-12 17:26:15
【问题描述】:

我是响应式表单的新手,并且努力将复选框的 value 动态设置为 true。 这是一个例子: 我从数据库中获取特定用户的预选水果值,当用户加载页面时需要检查这些水果。

我正在使用下面的 html 代码:

<ng-container>
<div class="form-check form-check-inline" style="display: block;" *ngFor="let control of fruitsArray.controls; let i = index;">
  <input *ngIf="i<11" class="form-check-input" [formControl]="control" type="checkbox" id="inlineCheckbox{{i}}" [checked]="fruitsCheck[i].checked">
  <label *ngIf="i<11" class="form-check-label" for="inlineCheckbox{{i}}">{{fruitsCheck[i].label}} <br /></label>
</div>

fruitsCheck 是一个包含标签和检查值的对象数组,如下所示:

fruitsCheck : Array<{label: string, checked: boolean}> = [];

fruitsCheck 将保存以下值:

0: {label: "Apple", checked: true},
1: {label: "Orange", checked: false},
2: {label: "Pineapple", checked: true},
3: {label: "Kiwi", checked: false}

使用上面的代码,我可以将适当的复选框设置为选中,但是在检查特定复选框控件的 value 时,它仍然显示为 false em>。我希望复选框不仅被选中,而且控件的值也被设置为 true。

我阅读了有关 patchValue 的信息,但不确定如何使用它将值设置为动态复选框。 提前感谢您的帮助!

【问题讨论】:

    标签: angular checkbox angular-reactive-forms reactive-forms


    【解决方案1】:

    Here 是一个以反应形式填充复选框列表的工作示例。

    import { Component, OnInit } from "@angular/core";
    import { FormArray, FormBuilder, FormGroup } from "@angular/forms";
    import { take } from "rxjs/operators";
    import { DataService } from "./data.service";
    
    @Component({
      selector: "my-app",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent implements OnInit {
      public fruitsForm: FormGroup;
    
      get fruitsArray() : FormArray {
        return this.fruitsForm.get('fruits') as FormArray
      } 
    
      constructor(private dataService: DataService, private fb: FormBuilder) {}
    
      ngOnInit(): void {
        this.dataService
          .getFruits()
          .pipe(take(1))
          .subscribe(fruits => {
            this.fruitsForm = this.fb.group({
              name: "Joe Bloggs",
              fruits: this.fb.array(fruits.map(f => this.fb.group(f)))
            });
          });
      }
    }
    

    HTML

    <ng-container *ngIf="fruitsForm">
        <form [formGroup]="fruitsForm">
            <input name="name" formControlName="name" />
            <div formArrayName="fruits">
                <div *ngFor="let fruit of fruitsArray.controls; let i = index" [formGroupName]="i">
                    <input type="checkbox" formControlName="selected" />
                    <label>{{fruit.value.name}}</label>
                </div>
            </div>
        </form>
        <br />
        <div>{{fruitsForm.value | json}}</div>
    </ng-container>
    

    我们已经使用服务和 RxJS delay 运算符模拟了从数据库中获取数据。

    import { Injectable } from "@angular/core";
    import { Observable, of } from "rxjs";
    import { delay } from "rxjs/operators";
    
    interface Fruit {
      id: number;
      name: string;
      selected: boolean;
    }
    
    @Injectable()
    export class DataService {
      constructor() {}
    
      public getFruits(): Observable<Fruit[]> {
        return of([
          {
            id: 1,
            name: "Apple",
            selected: true
          },
          {
            id: 2,
            name: "Pear",
            selected: false
          },
          {
            id: 3,
            name: "Orange",
            selected: false
          }
        ]).pipe(delay(250));
      }
    }
    

    我们使用FormBuilder 服务来构建我们的表单。

    我们将控件捆绑到一个名为fruitsFormFormGroup 中。

    在我们的FormGroup 中,fruits 是一个FormArray,允许许多输入。

    每个Fruit 对象都映射到一个新的FormGroup,我们Fruit 对象中的每个属性都将转换为一个FormControl

    fruitsArray getter 是为了更容易访问我们的表单属性。

    要将我们的模板连接到FormArray,我们使用formArrayName 指令。

    formGroupName 指令使用索引在我们的fruits FormGroup 中找到正确的FormGroup。要将我们的复选框连接到selected 控件,我们使用formControlName 指令。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-13
      • 2013-04-20
      • 2019-12-07
      • 1970-01-01
      • 2022-10-17
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多