Angular - 表單



表單用於處理使用者輸入資料。Angular 支援兩種型別的表單:模板驅動表單響應式表單。本節詳細解釋 Angular 8 表單。

模板驅動表單

模板驅動表單是使用模板中的指令建立的。它主要用於建立簡單的表單應用程式。讓我們簡要了解如何建立模板驅動表單。

配置表單

在瞭解表單之前,讓我們學習如何在應用程式中配置表單。要啟用模板驅動表單,首先需要在app.module.ts中匯入FormsModule。如下所示:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

//import FormsModule here
import { FormsModule } from '@angular/forms'; 

imports: [
   BrowserModule,
   AppRoutingModule,
   FormsModule   //Assign FormsModule
],

一旦匯入FormsModule,應用程式就準備好進行表單程式設計了。

建立簡單的表單

讓我們在 Angular 中建立一個示例應用程式(template-form-app)來學習模板驅動表單。

開啟命令提示符並使用以下命令建立新的 Angular 應用程式:

cd /go/to/workspace 
ng new template-form-app 
cd template-form-app

AppComponent中配置FormsModule,如下所示:

...

import { FormsModule } from '@angular/forms';

@NgModule({
   declarations: [
      AppComponent,
      TestComponent
   ],
   imports: [
      BrowserModule,
      FormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }

使用 Angular CLI 建立測試元件,如下所示:

ng generate component test

以上建立了一個新的元件,輸出如下:

CREATE src/app/test/test.component.scss (0 bytes)
CREATE src/app/test/test.component.html (19 bytes)
CREATE src/app/test/test.component.spec.ts (614 bytes)
CREATE src/app/test/test.component.ts (262 bytes)
UPDATE src/app/app.module.ts (545 bytes)

讓我們建立一個簡單的表單來顯示使用者輸入的文字。

將以下程式碼新增到test.component.html檔案:

<form #userName="ngForm" (ngSubmit)="onClickSubmit(userName.value)"> 
   <input type="text" name="username" placeholder="username" ngModel> 
   <br/> 
   <br/> 
   <input type="submit" value="submit"> 
</form>

這裡,我們在input文字欄位中使用了ngModel屬性。

test.component.ts檔案中建立onClickSubmit()方法,如下所示:

import { Component, OnInit } from '@angular/core';

@Component({
   selector: 'app-test',
   templateUrl: './test.component.html',
   styleUrls: ['./test.component.scss']
})

export class TestComponent implements OnInit {

   ngOnInit() {
   }
   onClickSubmit(result) {
      console.log("You have entered : " + result.username); 
   }
}

開啟 app.component.html 並更改內容如下:

<app-test></app-test>

最後,使用以下命令啟動您的應用程式(如果尚未啟動):

ng serve

現在,執行您的應用程式,您將看到以下響應:

Form

在輸入文字欄位中輸入Peter並提交。將呼叫onClickSubmit函式,並將使用者輸入的文字Peter作為引數傳送。onClickSubmit將在控制檯中列印使用者名稱,輸出如下:

Forms

響應式表單

響應式表單是在元件類內部建立的,因此也稱為模型驅動表單。每個表單控制元件在元件中都有一個物件,這提供了更大的控制和靈活性。響應式表單基於結構化資料模型。讓我們瞭解如何在 Angular 中使用響應式表單。

配置響應式表單

要啟用響應式表單,首先需要在app.module.ts中匯入ReactiveFormsModule。定義如下:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { FormsModule } from '@angular/forms';

//import ReactiveFormsModule here
import { ReactiveFormsModule } from '@angular/forms';

  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule, 
    ReactiveFormsModule   //Assign here
  ]

建立響應式表單

在開始建立響應式表單之前,我們需要了解以下概念:

  • FormControl: 定義單個表單控制元件的基本功能

  • FormGroup: 用於聚合集合表單控制元件的值

  • FormArray: 用於將表單控制元件的值聚合到陣列中

  • ControlValueAccessor: 充當表單 API 與 HTML DOM 元素之間的介面。

讓我們在 Angular 中建立一個示例應用程式(reactive-form-app)來學習模板驅動表單。

開啟命令提示符並使用以下命令建立新的 Angular 應用程式:

cd /go/to/workspace
ng new reactive-form-app
cd reactive-form-app

AppComponent中配置ReactiveFormsModule,如下所示:

...
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
   declarations: [
      AppComponent,
      TestComponent
   ],
   imports: [
      BrowserModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }

使用 Angular CLI 建立一個test元件,如下所示:

ng generate component test

以上建立了一個新的元件,輸出如下:

CREATE src/app/test/test.component.scss (0 bytes)
CREATE src/app/test/test.component.html (19 bytes)
CREATE src/app/test/test.component.spec.ts (614 bytes)
CREATE src/app/test/test.component.ts (262 bytes)
UPDATE src/app/app.module.ts (545 bytes)

讓我們建立一個簡單的表單來顯示使用者輸入的文字。

我們需要在TestComponent中匯入FormGroupFormControl類。

import { FormGroup, FormControl } from '@angular/forms';

test.component.ts檔案中建立onClickSubmit()方法,如下所示:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
   selector: 'app-test',
   templateUrl: './test.component.html',
   styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
   userName; 
   formdata;
   ngOnInit() { 
      this.formdata = new FormGroup({ 
         userName: new FormControl("Tutorialspoint")
      }); 
   } 
   onClickSubmit(data) {this.userName = data.userName;}
}

這裡:

  • 建立了formGroup的例項,並將其設定為區域性變數 form-data。

  • 建立了FormControl的例項,並將其設定為 form-data 中的一個條目。

  • 建立了一個onClickSubmit()方法,該方法使用其引數設定區域性變數userName

將以下程式碼新增到test.component.html檔案。

<div> 
   <form [formGroup]="formdata" (ngSubmit)="onClickSubmit(formdata.value)" > 
      <input type= text"  name="userName" placeholder="userName" 
         formControlName = "userName"> 
      <br/>
      <br/>
      <input type="submit"  value="Click here"> 
   </form>
</div> 
<p> Textbox result is: {{userName}} </p>

這裡:

  • 建立新的表單,並將其formGroup屬性設定為 formdata。

  • 建立新的輸入文字欄位,並將formControlName設定為 username。

  • 在表單中使用ngSubmit事件屬性,並將其值設定為 onClickSubmit() 方法。

  • onClickSubmit()方法獲取 form-data 值作為其引數。

開啟app.component.html並更改內容如下:

<app-test></app-test>

最後,使用以下命令啟動您的應用程式(如果尚未啟動):

ng serve

現在,執行您的應用程式,您將看到以下響應:

Nested response

在輸入文字欄位中輸入Tutorialspoint並提交。將呼叫onClickSubmit函式,並將使用者輸入的文字Peter作為引數傳送。

responses

我們將在下一章進行表單驗證。

廣告