Angular 4 表单
Angular 4 表单
在这一章中,我们将看到如何Angular 4中使用表单。我们将讨论两种处理表单的方式——模板驱动表单和模型驱动表单。
模板驱动表单
使用模板驱动的表单,大部分工作都在模板中完成;使用模型驱动的形式,大部分工作在组件类中完成。
现在让我们考虑使用模板驱动的表单。我们将创建一个简单的登录表单,添加电子邮件id、密码和提交按钮。首先,我们需要从@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,同样的内容也添加到了导入数组中,如代码所示。
现在让我们在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、密码和提交按钮,我们已经为其分配了type、name和placeholder。
在模板驱动的表单中,我们需要通过添加ngModel指令和name属性来创建模型表单控件。因我们希望Angular从表单中访问我们的数据,如上所示,将ngModel添加到该标签中。现在,如果我们需要获取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 4 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函数。当您点击表单提交按钮时,控件将进入上述功能。
浏览器的显示如下:
表单如下所示。让我们在其中输入数据,在提交的时候,email id已经输入。
电子email id显示在底部,如上图所示。
模型驱动的表单
在模型驱动的表单中,我们需要从@angular/forms导入ReactiveFormsModule,并在导入数组中使用它。
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中,我们需要为模型驱动的表单导入一些模块。例如,从“@angular/forms”导入{ FormGroup, FormControl}。
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 4 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用默认值初始化,以显示在表单中。如果你想的话,你可以把它留空。
这就是这些值在表单UI中的显示方式。
我们已经使用formdata来初始化表单值;我们需要在UI部分即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文件中,我们使用方括号中的formGroup作为表单;例如,[formGroup]=”formdata。提交时,该函数称为OnClickSubmit,为其传递formdata.value。
使用输入标签FormControlName。它给出了一个我们在app.component.ts文件中使用的值。
单击提交时,控件将传递给函数OnClickSubmit,该函数在app.component.ts中定义。
点击登录,该值将显示如上截图所示。
表单验证
现在让我们讨论使用模型驱动表单的表单验证。您可以使用内置表单验证,也可以使用自定义验证方法。我们将在表单中使用这两种方法。我们将继续前面一节中创建的相同示例。对于Angular 4,我们需要从@angular/forms导入验证器,如下所示。
import { FormGroup, FormControl, Validators} from '@angular/forms'
Angular具有内置的验证器,例如强制字段、最小长度、最大长度和正则表达式,这些将使用Validators模块访问。
您只需添加验证器或验证器数组,就可以判断某个特定字段是否为必填字段。
现在让我们在其中一个输入文本框中尝试同样的方法,即email id,我们添加了以下验证参数,
必填项
模式匹配
这就是代码如何在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 4 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中,您可以在输入字段中添加要验证的内容列表。现在,我们已经添加了required的和模式匹配的参数,只接收合法的电子邮件。
在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无效,按钮将保持禁用状态,用户将无法提交它。
让我们看看在浏览器中是如何工作的?
在上述情况下,输入的email id无效,因此登录按钮被禁用。现在让我们尝试输入有效的email id,看看有什么不同。
现在,输入的email id有效。因此,我们可以看到登录按钮被启用,用户将能够提交它。这样,输入的email 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 4 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;} }
在上面的例子中,我们已经创建了一个函数密码验证,并且在formcontrol - passwd: new FormControl("", this.passwordvalidation)中的前一节中也使用了这个函数密码验证。
在我们创建的函数中,我们将检查输入字符的长度是否合适。如果字符少于五个,它将返回{"passwd" : true}。如果字符超过五个,它将认为该字符有效,并且登录将被启用。
现在让我们看看这是如何在浏览器中显示的
我们在密码中只输入了三个字符,登录被禁用。要启用登录,我们需要五个以上的字符。现在让我们输入有效长度的字符并检查。
登录被启用,因为email id和密码都有效。当我们登录时,电子邮件显示在底部。