最近在學 Angular,他的 Form 相關模組挺有趣的,不過為了實現某些功能還是必須透過 JS 加工,這邊記錄一下怎麼綁 checkbox 的 cheked 結果到 FormBuilder 上。
html
| <h3>{{ form.value | json }}</h3> |
| <div [formGroup]="form"> |
| <input type="text" formControlName="name"> |
| <ng-container *ngFor="let hobby of hobbies"> |
| <label> <input type="checkbox" [value]="hobby.value" (click)="updateHobbies($event)"> |
| {{ hobby.name }} |
| </label> |
| </ng-container></div> |
ts
| import { Component, OnInit } from '@angular/core'; |
| import { FormArray, FormBuilder, FormControl } from '@angular/forms'; |
| |
| @Component({ |
| selector: 'app-checkbox', |
| templateUrl: './checkbox.component.html', |
| styleUrls: ['./checkbox.component.scss'] |
| }) |
| export class CheckboxComponent implements OnInit { |
| public form = this.fb.group({ |
| name: [''], |
| hobbies: this.fb.array([]) |
| }); |
| public hobbies: object[] = [ |
| { name: 'basketball', value: 'basketball' }, |
| { name: 'baseball', value: 'baseball' }, |
| { name: 'tennis', value: 'tennis' }, |
| ]; |
| |
| constructor( |
| private fb: FormBuilder |
| ) { } |
| |
| ngOnInit(): void { |
| } |
| |
| public updateHobbies(e): void { |
| const hobbies: FormArray = this.form.get('hobbies') as FormArray; |
| |
| if (e.target.checked) { |
| hobbies.push(this.fb.control(e.target.value)); |
| } else { |
| let i = 0; |
| |
| hobbies.controls.forEach((control: FormControl) => { |
| if (control.value === e.target.value) { |
| hobbies.removeAt(i); |
| |
| return; |
| } |
| |
| ++i; |
| }); |
| } |
| } |
| } |