Angular Template-driven form 表單提交及驗證範例。
環境:
- Windows 64 Bit
- Angular 7
開啟app.module.ts並在@NgModule的imports陣列加入FormsModule,此module用來提供表單需要的功能如NgForm,NgModel等。
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; // <-- 匯入FormsModule
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule // <-- 加入FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
修改app.component.ts如下。在原有的AppComponent類別上新增一個User類別,用來綁定app.component.html中表單欄位的值。
新增ngOnInit()方法初始化AppComponent.user物件。
新增submit()方法,當點擊app.component.html中的Submit按鈕時此方法會被觸發,並印出表單欄位輸入的user內容。
app.component.ts
import { Component, Input } from '@angular/core';
export class User {
constructor(
public name: string,
public password: string
) {}
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user : User;
ngOnInit() {
this.user = new User(null, null);
}
submit() {
console.log(this.user);
}
}
修改app.component.html如下。
在<form>宣告一個template reference variable (範本參考變數)#userForm為ngForm,則在此範本(app.component.html)內皆可以useForm存取此NgForm及其屬性。
在<form>增加ngSubmit的事件綁定,當點擊表單中的Submit按鈕時會觸發ngSubmit事件並執行綁定的templdate statement,也就是userForm.valid && submit()。
在<form>表單中設定姓名輸入欄位及密碼輸入欄位。輸入欄位要設定以下:
- 設定
name屬性名稱(e.g.name="password") - 宣告templdate reference variable為
ngModel(e.g.#password="ngModel") - 使用
ngModel雙向綁定至AppComponent.user的屬性(e.g.[(ngModel)]="user.password") - 設定為必填(
required="required)及最小輸入字數(minlength)。
在輸入欄位下新增驗證失敗訊息標籤並搭配*ngIf判斷是否顯示。當欄位驗證失敗(name.invalid)且欄位的值有變動(name.dirty)或欄位有focus過(name.touched)才會顯示。
在<form>表單中設定提交按鈕<button type="submit">。點擊提交按鈕會發出ngSubmit事件。
app.component.html
<h2>Angular Template-driven Form Demo</h2>
<form (ngSubmit)="userForm.valid && submit()" #userForm="ngForm">
<div>
<label>Name:
<input type="text"
name="name"
#name="ngModel"
[(ngModel)]="user.name"
required="required" minlength="3">
</label>
<span style="color:red;"
*ngIf="name.invalid && (name.dirty || name.touched)">必填</span>
</div>
<br>
<div>
<label>Password:
<input type="password"
name="password"
#password="ngModel"
[(ngModel)]="user.password"
required="required" minlength="5">
</label>
<span style="color:red;"
*ngIf="password.invalid && (password.dirty || password.touched)">必填</span>
</div>
<br>
<div>
<button type="submit">Submit</button>
</div>
</form>
以上設定完成後啟動專案,效果如下。
參考:
沒有留言:
張貼留言