Browse Source

自訂欄位同步驗證方法,表單陣列不得為空

範例程式有問題,此次commit無法使用,arrayCannotEmpty內部不可為null
master
HarveyChou 2 years ago
parent
commit
3c9aac7f93
  1. 17
      src/app/app.component.html
  2. 37
      src/app/app.component.ts
  3. 8
      src/app/validators/array-cannot-empty.validator.ts

17
src/app/app.component.html

@ -1,15 +1,10 @@
<div [formGroup]="form">
<div>
帳號:<input type="text" formControlName="id" />
<ng-container *ngIf="id.touched">
<span *ngIf="id.hasError('required')">帳號為必填欄位</span>
<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>
密碼:<input type="password" formControlName="password" />
</div>
<div>
<button type="reset">重設</button>
<button type="submit">登入</button>
</div>
<span *ngIf="tasks.hasError('cannotEmpty')">至少需要一筆工作事項</span>
</div>
<pre>{{ tasks.errors | json }}</pre>

37
src/app/app.component.ts

@ -1,10 +1,7 @@
import { Component } from '@angular/core';
import {
FormBuilder,
FormControl,
FormGroup,
Validators,
} from '@angular/forms';
import { FormArray, FormBuilder } from '@angular/forms';
import { arrayCannotEmpty } from './validators/array-cannot-empty.validator';
@Component({
selector: 'my-app',
@ -12,32 +9,14 @@ import {
styleUrls: ['./app.component.css'],
})
export class AppComponent {
// 方法一
// readonly form = new FormGroup({
// id: new FormControl('', [Validators.required]),
// password: new FormControl(''),
// });
// 方法二
// readonly form = new FormGroup({
// id: new FormControl('', { validators: [Validators.required] }),
// password: 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(''),
tasks: this.fb.array([], {
validators: [arrayCannotEmpty]?
}),
});
get id(): FormControl {
return this.form.get('id') as FormControl;
get tasks(): FormArray {
return this.form.get('tasks') as FormArray;
}
constructor(private fb: FormBuilder) {}

8
src/app/validators/array-cannot-empty.validator.ts

@ -0,0 +1,8 @@
import { FormArray, ValidationErrors } from '@angular/forms';
export function arrayCannotEmpty(formArray: FormArray): ValidationErrors | null {
if (formArray.length === 0) {
return { cannotEmpty: true };
}
return null;
}
Loading…
Cancel
Save