如何处理Angular 2 RC5中的复选框组?

时间:2016-08-26 06:11:59

标签: angular angular2-forms

我有一个表单,我希望用户编辑他想要收到的杂志订阅。代码如下:

组件:

export class OrderFormComponent {

    subscriptions = [
        {id: 'weekly', display: 'Weekly newsletter'},
        {id: 'monthly', display: 'Monthly newsletter'},
        {id: 'quarterly', display: 'Quarterly newsletter'},
    ];

    mySubs = [
        this.subscriptions[1]
    ]

    order = new FormGroup({
        subs: new FormArray(this.mySubs.map(sub => new FormControl(sub)), Validations.required) //Lost at this part
    });
}

模板:

<form [formGroup]="order">

<div formArrayName="subs">
    <label>Sign me up for newsletters</label>
    <p *ngFor="let s of subscriptions; let i=index">
        <input type="checkbox"  [value]="s.id" [formControlName]="i" /> {{ s.display }}
    </p>        
</div>

<div>
    <input type="checkbox" formControlName="agree" /> I agree to the terms and conditions.
</div>

{{ order.value | json }}

当我运行应用程序时,会显示三个复选框,但只检查一个(错误的一个)。被检查的人有一个标签,而其他人没有。

component output

我在这里做错了什么?

2 个答案:

答案 0 :(得分:5)

好的,我终于明白了。

在我的组件中,我有:

library(xlsx)

write.xlsx(dat.summary, "my_summary.xlsx", row.names=FALSE)

在视图中我有:

// The order retrieved from the server
subscription = {
    schedules: [{id: 'weekly', display: 'Weekly update'}],
}

//The FormGroup element
this.subscriptionForm = new FormGroup({
        //Here I fill up a FormArray with some FormControls initialized to the
        //currently selected schedules
        schedules: new FormArray(this.subscription.schedules.map(schedule => new FormControl(schedule)), Validators.minLength(1))
    });

这是类中的 <div> <label>Frequency</label> <p *ngFor="let schedule of viewData.schedules"> <input type="checkbox" [checked]="subscription.schedules.includes(schedule)" (change)="changeSchedules(schedule)"> {{ schedule.display }} </p> </div> 方法:

changeSchedules()

像魅力一样!表单按预期验证,在表单提交之前无需额外的方法来检索/合并订阅数组。

答案 1 :(得分:0)

你在实例化FormControl时犯了一个错误。不是为所有选项创建FormControl的新实例,而是只创建一个(通过迭代mySub)。将您的代码更改为此类(未经测试):

order = new FormGroup({
  // creating an array of form control with default values
  subs: new FormArray(this.subscriptions.map(sub => new FormControl(this.isSelectedSub(sub))), Validations.required)
});


//...
isSelectedSub(sub): boolean {
  return this.mySubs.indexOf(sub) >= 0;
}

您可能需要一个功能,在发送之前将复选框合并到一系列选定的杂志订阅中。

相关问题