开发学院

您的位置:首页>教程>正文

教程正文

Angular 6 表单

  在这一章中,我们将会看到窗体是如何在Angular 6中使用的。我们将讨论使用表单的两种方式:模板驱动表单和模型驱动表单。

模板驱动表单

  使用模板驱动的表单,大部分工作是在模板中完成的;对于模型驱动的表单,大部分工作是在组件类中完成的。

  现在让我们考虑使用模板驱动的表单。我们将创建一个简单的登录表单,并在表单中添加email id, password和提交按钮。首先,我们需要从@angular/core导入表单模块,这在app.module.ts中完成,如下所示

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { MyserviceService } from './myservice.service';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
   declarations: [
      SqrtPipe,
      AppComponent,
      NewCmpComponent,
      ChangeTextDirective
   ],
   imports: [
      BrowserModule,
      HttpModule,
      FormsModule,
      RouterModule.forRoot([
         {path: 'new-cmp',component: NewCmpComponent}
      ])
   ],
   providers: [MyserviceService],
   bootstrap: [AppComponent]
})
export class AppModule { }

  因此,在app.module.ts中,我们已经导入了FormsModule,并且它被添加到imports数组中,如突出显示的代码所示。

  现在让我们在app.component.html文件中创建我们的表单。

<form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)" >
   <input type = "text" name = "emailid" placeholder = "emailid" ngModel>
   <br/>
   <input type = "password" name = "passwd" placeholder = "passwd" ngModel>
   <br/>
   <input type = "submit" value = "submit">
</form>

  我们已经创建了一个简单的表单,带有输入标签,包括电子邮件id、密码和提交按钮。我们已经为它分配了类型、名称和占位符。

  在模板驱动的表单中,我们需要通过添加ngModel指令和name属性来创建模型表单控件。因此,只要我们希望Angular从表单中访问我们的数据,就可以向标签添加一个模型,如上所示。现在,如果我们必须读取emailid和passwd,我们需要在它上面添加ngModel

  如果您看到了,我们还将ngForm添加到#userlogin中。ngForm指令需要添加到我们创建的表单模板中。我们还在ClickSubmit上添加了函数,并为其分配了userlogin.value。

  现在让我们在app.component.ts中创建函数,并获取表单中输入的值。

import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 6 Project!';
   todaydate;
   componentproperty;
   constructor(private myservice: MyserviceService) { }
   ngOnInit() {
      this.todaydate = this.myservice.showTodayDate();
   }
   onClickSubmit(data) {
      alert("Entered Email id : " + data.emailid);
   }
}

  在上面的app.component.ts文件中,我们已经定义了onClickSubmit函数。当您点击表单提交按钮时,控件将进入上述功能。

  浏览器就是这样显示的

onclicksubmit_login.jpg

  表单如下所示。让我们在其中输入数据,在提交功能中,已经输入了电子邮件id。

email_entered_login.jpg

  电子邮件id显示在底部,如上图所示。

模型驱动形式

  在模型驱动的表单中,我们需要从@angular/forms导入反应表单模块,并在导入数组中使用它。

  app.module.ts中有一个更改。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
import { HttpModule } from '@angular/http';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { MyserviceService } from './myservice.service';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
   declarations: [
      SqrtPipe,
      AppComponent,
      NewCmpComponent,
      ChangeTextDirective
   ],
   imports: [
      BrowserModule,
      HttpModule,
      ReactiveFormsModule,
      RouterModule.forRoot([
         {
            path: 'new-cmp',
            component: NewCmpComponent
         }
      ])
   ],
   providers: [MyserviceService],
   bootstrap: [AppComponent]
})
export class AppModule { }

  在app.component.ts中,我们需要为模型驱动的表单导入一些模块。

import { FormGroup, FormControl } from '@angular/forms'.
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 6 Project!';
   todaydate;
   componentproperty;
   emailid;
   formdata;
   constructor(private myservice: MyserviceService) { }
   ngOnInit() {
      this.todaydate = this.myservice.showTodayDate();
      this.formdata = new FormGroup({
         emailid: new FormControl("angular@gmail.com"),
         passwd: new FormControl("abcd1234")
      });
   }
   onClickSubmit(data) {this.emailid = data.emailid;}
}

  变量formdata在类的开始初始化,同样的也用FormGroup初始化,如上所示。变量emailid和passwd用要在表单中显示的默认值进行初始化。如果你愿意,你可以把它留空。

  这就是这些值在表单用户界面中的显示方式。

form_ui.jpg

  我们已经使用表单数据来初始化表单值;我们需要在用户界面app.component.html中使用同样的方法。

<div>
   <form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
      <input type = "text" class = "fortextbox" name = "emailid" placeholder = "emailid" 
         formControlName="emailid">
      <br/>
      
      <input type = "password" class = "fortextbox" name="passwd" 
         placeholder = "passwd" formControlName = "passwd">
      <br/>
      
      <input type = "submit" class = "forsubmit" value = "Log In">
   </form>
</div>
<p>
   Email entered is : {{emailid}}
</p>

  在.html文件中,我们使用了方括号中的窗。提交时,该函数被称为onClickSubmit,为其传递formdata.value。

  使用输入标记formControlName。它被赋予一个我们在app.component.ts文件中使用的值。

  单击提交时,控件将传递给在app.component.ts文件中定义的onClickSubmit函数。

screenshot_onclicksubmit_event.jpg

表单验证

  现在让我们讨论使用模型驱动表单的表单验证。您可以使用内置的表单验证,也可以使用自定义验证方法。我们将在表单中使用这两种方法。我们将继续前面一节中创建的相同示例。对于Angular 4,我们需要从@angular/forms导入验证器,如下所示

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

  Angular有内置的验证器,如强制字段、最小长度、最大长度和模式。这些将使用验证器模块进行访问。

  如果某个特定字段是强制的,您可以只添加验证器或验证器数组来告诉Angular。

现在让我们在其中一个输入文本框上尝试同样的方法,即email id。对于email id,我们添加了以下验证参数:Required和Pattern matching

  这是代码在app.component.ts中进行验证的方式。

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 6 Project!';
   todaydate;
   componentproperty;
   emailid;
   formdata;
   ngOnInit() {
      this.formdata = new FormGroup({
         emailid: new FormControl("", Validators.compose([
            Validators.required,
            Validators.pattern("[^ @]*@[^ @]*")
         ])),
         passwd: new FormControl("")
      });
   }
   onClickSubmit(data) {this.emailid = data.emailid;}
}

  在Validators.compose中,您可以在输入字段中添加要验证的内容列表。现在,我们已经添加了必需的和模式匹配的参数,以便只接收有效的电子邮件。

  在app.component.html,如果任何表单输入无效,提交按钮将被禁用。这是按照以下方式完成的

<div>
   <form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
      <input type = "text" class = "fortextbox" name = "emailid" placeholder = "emailid" 
         formControlName = "emailid">
      <br/>
      <input type = "password" class = "fortextbox" name = "passwd" 
         placeholder = "passwd" formControlName = "passwd">
      <br/>
      <input type = "submit" [disabled] = "!formdata.valid" class = "forsubmit" 
         value = "Log In">
   </form>
</div>
<p>
   Email entered is : {{emailid}}
</p>

  对于提交按钮,我们已经在方括号中添加了disabled,它被赋予值- !formdata.valid。因此,如果formdata.valid无效,按钮将保持禁用状态,用户将无法提交它。

  让我们看看这在浏览器中是如何工作的

formdata_valid_event_output.jpg

  在上述情况下,输入的email id无效,因此登录按钮被禁用。现在让我们尝试输入有效的email id,看看有什么不同。

disabled_login_button.jpg

  现在,输入的电子邮件id是有效的。因此,我们可以看到登录按钮已启用,用户将能够提交它。这样,输入的电子邮件id显示在底部。

  现在让我们尝试使用相同的表单进行自定义验证。对于自定义验证,我们可以定义自己的自定义函数,并在其中添加所需的细节。我们现在将看到一个同样的例子。

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 6 Project!';
   todaydate;
   componentproperty;
   emailid;
   formdata;
   ngOnInit() {
      this.formdata = new FormGroup({
         emailid: new FormControl("", Validators.compose([
            Validators.required,
            Validators.pattern("[^ @]*@[^ @]*")
         ])),
         passwd: new FormControl("", this.passwordvalidation)
      });
   }
   passwordvalidation(formcontrol) {
      if (formcontrol.value.length < 5) {
         return {"passwd" : true};
      }
   }
   onClickSubmit(data) {this.emailid = data.emailid;}
}

  在上面的示例中,我们创建了一个函数密码验证,在form control passwd的上一节中也使用了该验证:new FormControl("", this.passwordvalidation).

  在我们创建的函数中,我们将检查输入字符的长度是否合适。如果字符少于五个,将返回如上所示的passwd为真-返回{ " passwd:true };。如果字符超过五个,它将认为它是有效的,并且登录将被启用。

  现在让我们看看这在浏览器中是如何显示的:

three_characters_entered_in_password.jpg

  我们在密码中只输入了三个字符,登录被禁用。要启用登录,我们需要五个以上的字符。现在让我们输入有效长度的字符并检查。

valid_id_password_enables_login.jpg

  由于email id和密码都有效,登录被启用。当我们登录时,电子邮件显示在底部。