From 2b72de571b6f6947998f39e8981c24b2002c88a4 Mon Sep 17 00:00:00 2001 From: HarveyChou Date: Tue, 8 Nov 2022 16:02:38 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A8=E5=96=AE=E9=99=A3=E5=88=97=E7=B5=90?= =?UTF-8?q?=E6=A7=8B=E7=9A=84=E6=93=8D=E4=BD=9C=20=E9=A0=90=E8=A8=AD?= =?UTF-8?q?=E6=95=B8=E9=87=8F=E5=8F=AA=E6=9C=83=E6=A0=B9=E6=93=9A=E5=8E=9F?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E6=95=B8=E9=87=8F=E5=8E=BB=E8=A8=AD=E5=AE=9A?= =?UTF-8?q?=20=E5=8C=85=E5=90=ABpush=20method=EF=BC=8C=E5=8F=AF=E4=BB=A5?= =?UTF-8?q?=E5=8A=A0=E5=85=A5=E6=96=B0=E7=9A=84Formgroup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/app.component.html | 22 +++++++++++++--------- src/app/app.component.ts | 35 +++++++++++++++++++++++++---------- 2 files changed, 38 insertions(+), 19 deletions(-) diff --git a/src/app/app.component.html b/src/app/app.component.html index 45bca65..258477c 100644 --- a/src/app/app.component.html +++ b/src/app/app.component.html @@ -1,11 +1,15 @@ -
-
工作事項:
-
工作內容:
-
- - - + + + +
+
+ +
工作事項:
+
工作內容:
+ +
+
-
{{form.value |json}}
-
{{form.dirty |json}}
+ +
{{ tasks.value | json }}
diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 38532ac..d50d3cf 100644 --- a/src/app/app.component.ts +++ b/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 { - - constructor(private fb: FormBuilder) { } - readonly form = this.fb.group({ - subject: this.fb.control(''), - content: this.fb.control(''), + form = this.fb.group({ + tasks: this.fb.array([]), }); + get tasks(): FormArray { + return this.form.get('tasks') as FormArray; + } + constructor(private fb: FormBuilder) { } onSetValue(): void { - this.form.setValue({ subject: 'Task A', content: '' }); + this.tasks.patchValue([ + { subject: 'Task A', content: 'Do something...' }, + { subject: 'Task B', content: 'Do something...' }, + ]) } - onPatchValue(): void { - this.form.patchValue({subject:'Task A'}); + + onAdd(): void{ + const group = this.fb.group({ + subject: this.fb.control(''), + content: this.fb.control(''), + }); + this.tasks.push(group); + } + + onRemove(index: number): void { + this.tasks.removeAt(index); } - onReset():void{ - this.form.reset({subject:'', content:''}); + + onClear(): void { + this.tasks.clear(); } }