Huangism
Huangism

Reputation: 16438

How to check multiple checkboxes programmatically in a formGroup on reactive form?

I am using Angular2 RC 5, and trying to implement a reactive form (model driven)

I defined the checkboxes like so

usageRights : new FormGroup({
     all_usage   : new FormControl( '' ),
     digital     : new FormControl( '' ),
     outdoor     : new FormControl( '' ),
     print       : new FormControl( '' ),
     radio       : new FormControl( '' ),
     tv          : new FormControl( '' )
})

There is a button and when it is clicked, I like to check all the checkboxes in the group. My current implementation is using a function on click of the button but I cannot figure out how I can check these checkboxes in my ts file

My checkAll function

checkAll( control, e ) {
    e.preventDefault();
    console.log(control);
}

control is the formGroup(usageRights) that contains all the checkboxes, and it logs fine. I believe I can just use a variable in combination with [checked], then update the variable when clicked on the button but I feel like this is not the proper way of doing this.

Someone please tell me how this should be done. I am stuck.

Upvotes: 2

Views: 1470

Answers (1)

Huangism
Huangism

Reputation: 16438

I figured it out

checkAll( control, e ) {
    e.preventDefault();

    for( let key in control.controls ) {
        control.controls[ key ].setValue( true );
    }
}

The setValue function is of formControl prototype More docs here https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

Leaving this here when other people get stuck on the same thing

Upvotes: 3

Related Questions