获取一组复选框中选中的值

  1. import { Component, OnInit } from '@angular/core';
  2. import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
  3. // 定义 Data 接口类型
  4. interface Data {
  5. name: string
  6. value: string
  7. }
  8. @Component({
  9. selector: 'app-checkbox',
  10. templateUrl: './checkbox.component.html',
  11. styleUrls: ['./checkbox.component.scss']
  12. })
  13. export class CheckboxComponent implements OnInit {
  14. Data: Array<Data> = [
  15. { name: "Pear", value: "pear" },
  16. { name: "Plum", value: "plum" },
  17. { name: "Kiwi", value: "kiwi" },
  18. { name: "Apple", value: "apple" },
  19. { name: "Lime", value: "lime" }
  20. ]
  21. form: FormGroup
  22. constructor(private fb: FormBuilder) {
  23. this.form = this.fb.group({
  24. checkArray: this.fb.array([])
  25. })
  26. }
  27. onChange(event: Event) {
  28. const target = event.target as HTMLInputElement
  29. const checked = target.checked
  30. const value = target.value
  31. const checkArray = this.form.get("checkArray") as FormArray
  32. if (checked) {
  33. checkArray.push(this.fb.control(value))
  34. } else {
  35. const index = checkArray.controls.findIndex(
  36. control => control.value === value
  37. )
  38. checkArray.removeAt(index)
  39. }
  40. }
  41. onSubmit() {
  42. console.log(this.form.value)
  43. }
  44. ngOnInit(): void {
  45. }
  46. }
  1. <form [formGroup]="form" (submit)="onSubmit()">
  2. <label *ngFor="let item of Data">
  3. <input type="checkbox" [value]="item.value" (change)="onChange($event)" />
  4. {{ item.name }}
  5. </label>
  6. <button>提交</button>
  7. </form>

获取单选框中选中的值

  1. import { Component, OnInit } from '@angular/core';
  2. import { FormBuilder, FormGroup } from '@angular/forms';
  3. @Component({
  4. selector: 'app-checkbox',
  5. templateUrl: './checkbox.component.html',
  6. styleUrls: ['./checkbox.component.scss']
  7. })
  8. export class CheckboxComponent implements OnInit {
  9. form: FormGroup
  10. constructor(public fb: FormBuilder) {
  11. this.form = this.fb.group({ gender: "" })
  12. }
  13. onSubmit() {
  14. console.log(this.form.value)
  15. }
  16. ngOnInit(): void {
  17. }
  18. }
  1. <form [formGroup]="form" (submit)="onSubmit()">
  2. <input type="radio" value="male" formControlName="gender" /> Male
  3. <input type="radio" value="female" formControlName="gender" /> Female
  4. <button type="submit">Submit</button>
  5. </form>