1

In Angular 7 using reactive forms, I'm trying to build an array of checkboxes. I'd like to use an array of objects instead of just [true, true, false] as a result. My objects have a name, an id and a boolean selected property.

In my TypeScript:

myForm: FormGroup

constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
        myOptionsArray: this.fb.array([
            {
                id: 1,
                name: 'Option 1',
                selected: false
            },
            {
                id: 2,
                name: 'Option 2',
                selected: true
            },
            {
                id: 3,
                name: 'Option 3',
                selected: false
            })
        ])
    })
}

My template:

<form [formGroup]="myForm">
    <div formArrayName="myOptionsArray">
        <div *ngFor="let myOption of myOptionsArray.controls; let i = index">
            <div formGroupName="{{ i }}">
                <input name="i" type="checkbox" [formControl]="myOption" />
                <label> {{ myOption.get('name').value }} </label>
            </div>
        </div>
    </div>
</form>

I cannot get the selected property in the corresponding object to be updated. How do I manage to get each checkbox to update only the selected property in the array?

1

1 Answer 1

5

Being directed to a question already answered before solved my problem. For anyone wanting to know: I needed to wrap the objects in a formbuilder group, which made the fields accessible in the form. My working code:

myForm: FormGroup

constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
        myOptionsArray: this.fb.array([
            this.fb.group({
                id: 1,
                name: 'Option 1',
                selected: false
            }),
            this.fb.group({
                id: 2,
                name: 'Option 2',
                selected: true
            }),
            this.fb.group({
                id: 3,
                name: 'Option 3',
                selected: false
            })
        ])
    })
}

The updated template:

<form [formGroup]="myForm">
    <div formArrayName="myOptionsArray">
        <div *ngFor="let myOption of myOptionsArray.controls; let i = index">
            <div formGroupName="{{ i }}">
                <input type="checkbox" [formControl]="myOption.get('selected')" />
                <label> {{ myOption.get('name').value }} </label>
            </div>
        </div>
    </div>
</form>
Sign up to request clarification or add additional context in comments.

1 Comment

Super helpful mate, i was going all kinda of wacky mapping to object properties as I couldnt get anything else but true/false working for a while. Top marks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.