2016-08-26 35 views
4

我有一個表單,我希望用戶編輯他希望收到的雜誌訂閱。代碼如下:如何處理Angular 2 RC5中的複選框組?

組件:

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

我在做什麼錯在這裏?

回答

5

好吧,我終於明白了。

在我的部分,我有:

// 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()方法的類:

changeSchedules(schedule: any) { 
    var currentScheduleControls: FormArray = this.subscriptionForm.get('schedules') as FormArray; 
    var index = currentScheduleControls.value.indexOf(schedule); 
    if(index > -1) currentScheduleControls.removeAt(index) //If the user currently uses this schedule, remove it. 
    else currentScheduleControls.push(new FormControl(schedule)); //Otherwise add this schedule. 
} 

工程就像一個魅力!表單按預期進行驗證,在提交表單前無需額外的方法來檢索/合併訂閱數組。

+0

'[checked] =「subscription.schedules.includes(schedule)」''因爲'subscription.schedules'永遠不會被修改嗎? – Kevin

+0

我真的不記得其他所有東西如何連線起作用。我從Angular開始。對不起:/ – kshep92

+0

很好的答案!謝謝。它允許我避免爲類似的任務 –

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; 
} 

而且你可能需要一個函數在發送之前鞏固複選框以選擇訂閱雜誌的數組。