How to handle a group of flags in Angular 2 RC5?

I have a form where I would like the user to edit the magazine subscriptions that he would like to receive. The code is as follows:

component:

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

Template:

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

When I launch the application, three flags are displayed, but only one of them is checked (in this case, erroneous). The one who checked has a label, while the others do not.

component output

What am I doing wrong here?

+4
source share
2 answers

Good, so I finally figured it out.

In my component, I:

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

In the view, I have:

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

And here is the method changeSchedules()in the class:

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

! , , , / .

+5

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

, , .

0

Source: https://habr.com/ru/post/1652558/


All Articles