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) {} }