From 1b854b85d3bb4807848b071364574f116b9231fa Mon Sep 17 00:00:00 2001 From: HarveyChou Date: Tue, 8 Nov 2022 11:12:13 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A8=E5=96=AE=E6=AC=84=E4=BD=8D=E9=A9=97?= =?UTF-8?q?=E8=AD=89validator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/app.component.html | 18 +++++++++----- src/app/app.component.ts | 48 +++++++++++++++++++++++++------------- 2 files changed, 44 insertions(+), 22 deletions(-) diff --git a/src/app/app.component.html b/src/app/app.component.html index 599835b..dd49e59 100644 --- a/src/app/app.component.html +++ b/src/app/app.component.html @@ -1,9 +1,15 @@ -
-
- - - +
+
+ 帳號: + + 帳號為必填欄位
+
+ 密碼: +
+
+ + +
-
{{form.value| json}}
diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 777fab3..9151156 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -1,28 +1,44 @@ import { Component } from '@angular/core'; -import { FormArray, FormControl, FormGroup } from '@angular/forms'; - +import { + FormBuilder, + FormControl, + FormGroup, + Validators, +} from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) -export class AppComponent { - readonly form = new FormGroup({ - Tasks: new FormArray([]), - }); +export class AppComponent { + // 方法一 + // 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(''), + // }); + + // 方法三 + // 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(''), + }); - ngOnInit(): void{ - this.tasks.push(//注意此push用法 - new FormGroup({ - Subject: new FormControl(), - Content: new FormControl(), - }) - ); + get id(): FormControl { + return this.form.get('id') as FormControl; } + constructor(private fb: FormBuilder) {} }