Browse Source

表單欄位驗證validator

master
HarveyChou 2 years ago
parent
commit
1b854b85d3
  1. 16
      src/app/app.component.html
  2. 46
      src/app/app.component.ts

16
src/app/app.component.html

@ -1,9 +1,15 @@
<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"/>
<div>
帳號:<input type="text" formControlName="id" />
<ng-container *ngIf="id.touched">
<span *ngIf="id.hasError('required')">帳號為必填欄位</span>
</ng-container>
</div>
<div>
密碼:<input type="password" formControlName="password" />
</div>
<div>
<button type="reset">重設</button>
<button type="submit">登入</button>
</div>
</div>
<pre>{{form.value| json}}</pre>

46
src/app/app.component.ts

@ -1,6 +1,10 @@
import { Component } from '@angular/core';
import { FormArray, FormControl, FormGroup } from '@angular/forms';
import {
FormBuilder,
FormControl,
FormGroup,
Validators,
} from '@angular/forms';
@Component({
selector: 'my-app',
@ -8,21 +12,33 @@ import { FormArray, FormControl, FormGroup } from '@angular/forms';
styleUrls: ['./app.component.css'],
})
export class AppComponent {
readonly form = new FormGroup({
Tasks: new FormArray([]),
});
// 方法一
// readonly form = new FormGroup({
// id: new FormControl('', [Validators.required]),
// password: new FormControl(''),
// });
get tasks(): FormArray{
return this.form.get('Tasks') as FormArray;
}
// 方法二
// readonly form = new FormGroup({
// id: new FormControl('', { validators: [Validators.required] }),
// password: new FormControl(''),
// });
ngOnInit(): void{
this.tasks.push(//注意此push用法
new FormGroup({
Subject: new FormControl(),
Content: new FormControl(),
})
);
// 方法三
// readonly form = this.fb.group({
// id: this.fb.control('', [Validators.required]),
// password: this.fb.control('')
// });
// 方法四
readonly form = this.fb.group({
id: this.fb.control('', { validators: [Validators.required] }),
password: this.fb.control(''),
});
get id(): FormControl {
return this.form.get('id') as FormControl;
}
constructor(private fb: FormBuilder) {}
}
Loading…
Cancel
Save