Browse Source

表單陣列結構的操作

預設數量只會根據原模型數量去設定
包含push method,可以加入新的Formgroup
master
HarveyChou 2 years ago
parent
commit
2b72de571b
  1. 22
      src/app/app.component.html
  2. 33
      src/app/app.component.ts

22
src/app/app.component.html

@ -1,11 +1,15 @@
<div [formGroup]="form">
<div>工作事項:<input type="text" formControlName="subject" /></div>
<div>工作內容:<input type="text" formControlName="content" /></div>
<div>
<button type="button" (click) = "onReset()">Reset</button>
<button type="button" (click) = "onSetValue()">Set Value</button>
<button type="button" (click) = "onPatchValue()">Patch Value</button>
<button type="button" (click)="onSetValue()">Set</button>
<button type="button" (click)="onAdd()">Add</button>
<button type="button" (click)="onClear()">Clear</button>
<div class="form" [formGroup]="form">
<div formArrayName="tasks" *ngFor="let control of tasks.controls; let index = index">
<ng-container [formGroupName]="index">
<div>工作事項:<input type="text" formControlName="subject" /></div>
<div>工作內容:<input type="text" formControlName="content" /></div>
<button type="button" (click)="onRemove(index)">Remove</button>
<hr>
</ng-container>
</div>
</div>
<pre>{{form.value |json}}</pre>
<pre>{{form.dirty |json}}</pre>
<pre>{{ tasks.value | json }}</pre>

33
src/app/app.component.ts

@ -1,6 +1,7 @@
import { Component, OnDestroy, OnInit } from '@angular/core';
import {
AbstractControl,
FormArray,
FormBuilder,
FormControl,
ValidationErrors,
@ -15,20 +16,34 @@ import { debounce, debounceTime, distinctUntilChanged, filter, map } from 'rxjs/
styleUrls: ['./app.component.css'],
})
export class AppComponent {
form = this.fb.group({
tasks: this.fb.array([]),
});
get tasks(): FormArray {
return this.form.get('tasks') as FormArray;
}
constructor(private fb: FormBuilder) { }
readonly form = this.fb.group({
onSetValue(): void {
this.tasks.patchValue([
{ subject: 'Task A', content: 'Do something...' },
{ subject: 'Task B', content: 'Do something...' },
])
}
onAdd(): void{
const group = this.fb.group({
subject: this.fb.control(''),
content: this.fb.control(''),
});
onSetValue(): void {
this.form.setValue({ subject: 'Task A', content: '' });
this.tasks.push(group);
}
onPatchValue(): void {
this.form.patchValue({subject:'Task A'});
onRemove(index: number): void {
this.tasks.removeAt(index);
}
onReset():void{
this.form.reset({subject:'', content:''});
onClear(): void {
this.tasks.clear();
}
}
Loading…
Cancel
Save