如何使用Angular2 ReactiveFormsModule将数组绑定到复选框?

时间:2016-12-08 09:57:07

标签: javascript forms angular checkbox

我是Angular2的新手(昨天开始)而不是之前的Angular用户。我的问题是如何将数组绑定到ReactiveFormsModule中的复选框? 以下是我遗失的拼图代码。

<!-- profile.ts -->
export class UserProfileComponent {
    status = {
        ready: false,
        saving: false
    };
    form: FormGroup;
    masterData = {
        skills: [{ id: 'js', text: 'Javascript' }, { id: 'cs', text: 'C#' }]
    };
    constructor(FB: FormBuilder) {
        let self = this;

        self.form = FB.group({
            name: new FormControl('', Validators.required)
            , gender: new FormControl('', Validators.required)
            , skills: new FormArray([])
        })
        self.getProfile()
            .then(profile => {
                return self.loadFormData(profile);
            }).then(() => {
                this.status.ready = true
            });
    }
    getProfile() {
        return new Promise((done, fail) => {
            let sample = { name: 'me', gender: 'm', skills: ['js']};
            done(sample);
        })
    }
    loadFormData({ name, gender, skills = []}) {
        let self = this
            , form = self.form

        return new Promise((done, fail) => {
            form.get('name').setValue(name);
            form.get('gender').setValue(gender);

            skills.reduce((array: FormArray, skill: string) => {
                array.push(new FormControl(skill));
                return array;
            }, form.get('skills'));
            done();
        });
    }
    selectSkill (event, skill) {
        let skills = this.form.get('skills')
            , checked = event.target.checked
            ;

        let index = skills.value.indexOf(skill);
        if (checked === true && index < 0) {
            skills.push(new FormControl(skill));
        } else if (checked === false && index >= 0) {
            skills.removeAt(index);
        }
    }   
};  


<!-- 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>Skill {{ skills }}</label>
        </div>
        <div *ngFor="let skill of masterData.skills">
            <div class="checkbox-inline"><label>
                <input type="checkbox" name="skill" (change)="selectSkill($event, skill.id)"> {{ skill.text }}
            </label></div>
        </div>
        <div>
            <button type="submit" class="btn" [disabled]="form.invalid">Save</button>
        </div>
    </form >
</div>

根据我的示例数据,除了我不知道如何在表单加载后检查技能复选框时,一切正常吗?

1 个答案:

答案 0 :(得分:-1)

您必须使用FormArrayName指令:

// Compoenent

public allSkills = [
  { value : 'cs', label : 'C#' },
  { value : 'js', label : 'Javascript' }
];

constructor(FB: FormBuilder) {
    this.form = FB.group({
        name: new FormControl('', Validators.required),
        gender: new FormControl('', Validators.required),
        skills: new FormArray([])
    });
    for(let skill on this.allSkills) {
      this.form.get('skills').push(new FormControl());
    }
}

// HTML

<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 formArrayName="skills">
    <div class="checkbox-inline" *ngFor="let skill of skills.controls; let i=index">
      <label>
        <input type="checkbox" [formControlName]="i" [value]="allSkills[i]['value']"/> {{allSkills[i]['label']}}
      </label>
    </div>
  </div>
  <button type="submit" class="btn" [disabled]="form.invalid"> Save </button>
</form>