Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
937 views
in Technique[技术] by (71.8m points)

angular2 forms - Angular how to get the multiple checkbox values?

I m using a checkbox in Angular to select more than one element and I'm trying to get the value of that checkbox for submitting.

Instead I'm getting the value those values as an array of true-s. That's what I've tried:

export class CreateSessionComponent implements OnInit {
  form : FormGroup ;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.form = this.formBuilder.group({
      userdata :  new FormArray([
        new FormControl('', Validators.required)
      ])
    })
  }
}

userdata is a dynamic array populated from a database.

<div formArrayName="useremail; let k = index">
  <div *ngFor="let data of userdata">
    <div>
      <input type="checkbox" name="useremail" formControlName ="{{k}}" [value]="data.email">{{data.email}}
    </div>
  </div>
</div> 
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you have several values you want to use, you need to use an FormArray, since FormControl can only capture one value.

Start with declaring an empty formArray:

this.myForm = this.fb.group({
  useremail: this.fb.array([])
});

Iterate the your emails, and watch for the change event and pass the respective email and event to a method onChange where you check if it's checked, then add the respective email to the formarray, if it's unchecked, remove the chosen email from the form array:

<div *ngFor="let data of emails">
  <input type="checkbox" (change)="onChange(data.email, $event.target.checked)"> {{data.email}}<br>
</div>

And onChange:

onChange(email:string, isChecked: boolean) {
  const emailFormArray = <FormArray>this.myForm.controls.useremail;

  if(isChecked) {
    emailFormArray.push(new FormControl(email));
  } else {
    let index = emailFormArray.controls.findIndex(x => x.value == email)
    emailFormArray.removeAt(index);
  }
}

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...