首页 > 解决方案 > 每次交互的形式重新生成,角度形式

问题描述

我在使用 Angular 表单时遇到问题。问题是一个复选框,其中包含一些值(大约 10)。我有一个项目,我用一些已经选择的值推入这个表格。所以我使用表格来编辑/更新这个项目。

我的复选框现在可以显示在编辑之前选择了复选框中的哪些值。此处示例:https ://gyazo.com/3cda89f3fc5c42de690fd8803274990b (悬停显示)

但是当我尝试选择一个新的复选框值时,它每次都会重新生成整个复选框,我不知道为什么。

也许我以错误的方式填写表格,我正在创建这样的表格:

<div class="form-group row">
        <div class="col">
            <label for="">Typer af data der indhentes:</label>
            <div formArrayName="DataTypes"
                 *ngFor="let test of this.createWhatItemData().controls; let j=index"
                 class="form-group">
                <div>
                    <div class="form-check">
                        <label class="form-check-label">
                            <input type="hidden" />
                            <input type="checkbox" class="form-check-input" [checked]="test.value.selected" />
                            {{whatItemDataTypes[j].Name}}
                        </label>
                    </div>
                </div>
            </div>
        </div>
    </div>

然后像这样初始化和填充:

private initFormWhatComponent() {
        this.form2 = this.formBuilder2.group({
            ConsentWhatItemDirection: this.whatItem.ConsentWhatItemDirection,
            ConsentWhatItemType: this.whatItem.ConsentWhatItemType,
            OrganizationIdentifier: this.whatItem.OrganizationIdentifier,
            Name: this.whatItem.Name,
            Description: this.whatItem.Description,
            DataTypes: this.formBuilder2.array(this.whatItem.DataTypes)
        });

        this.addWhatItemFormGroupWhatComponent(this.whatItem);
    }

这是为了将所有已选择的值放入我的复选框,如果我控制台日志,例如。每次我与表单交互时,它都会记录此功能中的“测试”。

createWhatItemData() {
        let _formArray = this.formBuilder2.array(
            this.whatItemDataTypes.map(s => {
                return this.formBuilder2.group({
                    selected: this.whatItem.DataTypes.some(x => x.Id == s.Id),
                    Id: s.Id,
                });
            })
        );
        return _formArray
    }

从数据库中获取可供选择的值,然后与发送到表单的项目值合并在一起。

谁能帮我修复复选框,以便我可以选择新值然后更新我的项目?

提前致谢。

标签: javascriptangularformarray

解决方案


  private initFormWhatComponent() {
    this.form2 = this.formBuilder2.group({
        ConsentWhatItemDirection: this.whatItem.ConsentWhatItemDirection,
        ConsentWhatItemType: this.whatItem.ConsentWhatItemType,
        OrganizationIdentifier: this.whatItem.OrganizationIdentifier,
        Name: this.whatItem.Name,
        Description: this.whatItem.Description,
        DataTypes: this.formBuilder2.array(this.whatItem.DataTypes)
    });

    this.addWhatItemFormGroupWhatComponent(this.whatItem);
    //return anything in here..
}

推荐阅读