jeudi 8 décembre 2016

How to bind an array to checkbox using Angular2 ReactiveFormsModule?

I am new to Angular2 (started yesterday) and not an Angular user before this. My question is how can I 2 way bind an array to checkbox in ReactiveFormsModule? Below is my missing piece puzzle code.

// profile.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormControl, FormArray, Validators, FormBuilder } from '@angular/forms';    
@Component({
    selector: 'userProfile',
    templateUrl: 'profile.html',
    // providers: []
})
export class ProfileComponent {
    form : FormGroup;        
    constructor(FB: FormBuilder) {
        this.form = FB.group({
            name: new FormControl('', Validators.required)
            , gender: new FormControl('', Validators.required)
            , skills: new FormArray([])
        });
    }
    submitForm(value: any) {
        let self = this 
            , form = self.form
            , data = form.value
            ; 

        // expected structure 
        // { name: 'simon', gender: 'm', skills: ['js', 'cs'] }
        console.log('data: ', data);
    }
};

`

<!-- profile.html -->
<div class="title">Profile</div>
<div>
    <form [formGroup]="form" (ngSubmit)="submitForm()">
        <div class="form-group">
            <label for="name">Name</label>
            <input formControlName="name" name="name" class="form-control" placeholder="Name" type="text">
        </div>
        <div class="form-group">
            <label>Gender</label>
        </div>
        <div class="radio-inline">
            <label><input type="radio" name="gender" value="m" formControlName="gender"> Male</label>
        </div>
        <div class="radio-inline">
            <label><input type="radio" name="gender" value="f" formControlName="gender"> Female</label>
        </div>
        <div class="form-group">
            <label>Skills</label>
        </div>
        <div class="checkbox-inline">
            <label>
                <input type="checkbox" name="skills" value="js" formControlName="skills"> Javascript
            </label>
        </div>
        <div class="checkbox-inline">
            <label>
                <input type="checkbox" name="skills" value="cs"formControlName="skills"> C#
            </label>
        </div>
        <div>
            <button type="submit" class="btn" [disabled]="form.invalid">Save</button>
        </div>
    </form >
</div>

Both name(textbox) and gender(radio) works. But what is the missing part for skills(checkbox)?

Aucun commentaire:

Enregistrer un commentaire