>
密鑰概念:
required
minlength
表格提交處理:FormControl
將事件綁定到有效數據捕獲和處理的組件方法。 ngSubmit
設置:
>本教程使用Bootstrap進行樣式。 這是整合它的方法:
> 安裝bootstrap:
在您的項目目錄中,運行。>>配置角cli:在您的npm install bootstrap@next
文件中,添加樣式錶鍊接到bootstrap:
import formsmodule:angular.json
在
"styles": [ "../node_modules/bootstrap/dist/css/bootstrap.css" ]
>
app.module.ts
FormsModule
@angular/forms
>模板驅動的表單:
import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, FormsModule, // ... other imports ] })
創建模板參考變量的使用,然後將表單提交綁定到組件方法。 屬性確保按鈕不活動直到表單有效為止。
創建表單輸入和驗證:
<form #companyForm="ngForm" (ngSubmit)="submitCompany(companyForm.value)"> <!-- Form fields here --> <button class="btn btn-primary" type="submit" [disabled]="!companyForm.valid">Submit</button> </form>
"styles": [ "../node_modules/bootstrap/dist/css/bootstrap.css" ]
此顯示ngModel
用於雙向數據綁定,required
>和minlength
>驗證器,以及基於companyName.touched
>和companyName.errors
>的條件錯誤顯示。
component's 方法:submitCompany
import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, FormsModule, // ... other imports ] })
對於更複雜的帳戶註冊表格,反應性形式提供了更大的控制。
>導入ReactiveFormsModule:
在您的中,來自>。
在組件中創建形式控件:app.module.ts
ReactiveFormsModule
@angular/forms
在模板中形式:
<form #companyForm="ngForm" (ngSubmit)="submitCompany(companyForm.value)"> <!-- Form fields here --> <button class="btn btn-primary" type="submit" [disabled]="!companyForm.valid">Submit</button> </form>
形式輸入字段:
<input type="text" class="form-control" name="companyName" ngModel #companyName="ngModel" required minlength="3"> <div *ngIf="companyName.touched && companyName.errors"> <div class="alert alert-danger" *ngIf="companyName.errors.required">Company name is required</div> <div class="alert alert-danger" *ngIf="companyName.errors.minlength">Company name must be at least {{ companyName.errors.minlength.requiredLength }} characters long</div> </div>
>
請記住調整代碼片段以匹配您的特定表單字段和要求。 這種詳細的解釋為構建Angular的簡單和復雜形式提供了堅實的基礎。
以上是快速創建簡單而強大的角形式的詳細內容。更多資訊請關注PHP中文網其他相關文章!