diff --git a/src/app/app.component.html b/src/app/app.component.html index dd49e59..0ede04b 100644 --- a/src/app/app.component.html +++ b/src/app/app.component.html @@ -1,15 +1,10 @@
{{ tasks.errors | json }}diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 9151156..36232db 100644 --- a/src/app/app.component.ts +++ b/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) {} diff --git a/src/app/validators/array-cannot-empty.validator.ts b/src/app/validators/array-cannot-empty.validator.ts new file mode 100644 index 0000000..ad9ada6 --- /dev/null +++ b/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; +}