Browse Source

響應式表單> 利用FormArray建立表單陣列

master
HarveyChou 2 years ago
parent
commit
9241462772
  1. 14
      src/app/app.component.html
  2. 18
      src/app/app.component.ts

14
src/app/app.component.html

@ -1,9 +1,9 @@
<div [formGroup]="form">
<div>帳號:<input type="text" formControlName="id" /></div>
<div>密碼:<input type="password" formControlName="password" /></div>
<div>
<button type="reset">重設</button>
<button type="submit">登入</button>
<div [formGroup] = "form">
<div formArrayName="Tasks" *ngFor="let control of tasks.controls; let index = index">
<ng-container [formGroupName]="index">
<input type="text" placeholder="主旨" formControlName="Subject"/>
<input type="text" placeholder="內容" formControlName="Content"/>
</ng-container>
</div>
</div>
<pre>{{ form.value | json }}</pre>
<pre>{{form.value| json}}</pre>

18
src/app/app.component.ts

@ -1,5 +1,5 @@
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { FormArray, FormControl, FormGroup } from '@angular/forms';
@Component({
@ -9,8 +9,20 @@ import { FormControl, FormGroup } from '@angular/forms';
})
export class AppComponent {
readonly form = new FormGroup({
id:new FormControl(),
password: new FormControl(),
Tasks: new FormArray([]),
});
get tasks(): FormArray{
return this.form.get('Tasks') as FormArray;
}
ngOnInit(): void{
this.tasks.push(//注意此push用法
new FormGroup({
Subject: new FormControl(),
Content: new FormControl(),
})
);
}
}
Loading…
Cancel
Save