在本章中,我們將學(xué)習(xí)如何創(chuàng)建表單。 我們將在我們的示例中使用以下類和指令。
來(lái)自Bootstrap的form-group,form-control和btn類。
用于數(shù)據(jù)綁定的[(ngModel)]和用于跟蹤我們的控制狀態(tài)的NgControl指令。
NgControl是NgForm指令族中的一個(gè),用于驗(yàn)證和跟蹤表單元素。
ngSubmit偽指令用于處理表單的提交。
下面的例子描述了如何在Angular 2中創(chuàng)建一個(gè)表單:
<html> <head> <title>Contact Form</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" rel="external nofollow" target="_blank" > <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/es6-shim.min.js"></script> <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system-polyfills.js"></script> <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2-polyfills.js"></script> <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system.js"></script> <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/typescript.js"></script> <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/Rx.js"></script> <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2.dev.js"></script> <script> System.config({ transpiler: 'typescript', typescriptOptions: { emitDecoratorMetadata: true }, packages: {'app': {defaultExtension: 'ts'}} }); System.import('/angular2/src/app/main') .then(null, console.error.bind(console)); </script> </head> <body> <my-app>Loading...</my-app> </body> </html>
上述代碼包括以下配置選項(xiàng):
您可以使用typescript版本配置index.html文件。在使用transpiler選項(xiàng)運(yùn)行應(yīng)用程序之前,SystemJS將TypeScript轉(zhuǎn)換為JavaScript。
如果在運(yùn)行應(yīng)用程序之前沒(méi)有翻譯到JavaScript,您可能會(huì)看到瀏覽器中隱藏的編譯器警告和錯(cuò)誤。
當(dāng)設(shè)置emitDecoratorMetadata選項(xiàng)時(shí),TypeScript會(huì)為代碼的每個(gè)類生成元數(shù)據(jù)。如果不指定此選項(xiàng),將生成大量未使用的元數(shù)據(jù),這會(huì)影響文件大小和對(duì)應(yīng)用程序運(yùn)行時(shí)的影響。
Angular 2包括來(lái)自app文件夾的包,其中文件將具有.ts擴(kuò)展名。
接下來(lái)它將從應(yīng)用程序文件夾加載主組件文件。如果沒(méi)有找到主要組件文件,那么它將在控制臺(tái)中顯示錯(cuò)誤。
當(dāng)Angular調(diào)用main.ts中的引導(dǎo)函數(shù)時(shí),它讀取Component元數(shù)據(jù),找到“app”選擇器,找到一個(gè)名為app的元素標(biāo)簽,并在這些標(biāo)簽之間加載應(yīng)用程序。
要運(yùn)行代碼,您需要以下TypeScript(.ts)文件,您需要保存在應(yīng)用程序文件夾下。
form_main.tsimport {bootstrap} from 'angular2/platform/browser'; import {AppComponent} from "./data_binding_app.component"; bootstrap(AppComponent);contact.ts
export class Contact { constructor( public firstname: string, public lastname: string, public country: string, public phone: number ) { } }
Contact類包含在我們的表單中使用的名字,姓氏,國(guó)家和電話。
forms_app.component.tsimport {Component} from 'angular2/core'; import {ContactComponent} from './contact-form.component' @Component({ selector: 'my-app', template: '', directives: [ContactComponent] }) export class AppComponent { }
@Component是一個(gè)裝飾器,它使用配置對(duì)象來(lái)創(chuàng)建組件。
選擇器創(chuàng)建組件的實(shí)例,在父HTML中找到<my-app>標(biāo)記。
該模板告訴Angular渲染為視圖。
上面的app.component.ts將導(dǎo)入ContactComponent組件并使用指令來(lái)包含組件。
import {Component} from 'angular2/core'; import {NgForm} from 'angular2/common'; import { Contact } from './contact'; @Component({ selector: 'contact-form', templateUrl: 'app/contact-form.component.html' }) export class ContactComponent { countries = ['India', 'Australia', 'England', 'South Africa', 'USA', 'Japan', 'Singapore']; contact = new Contact('Ravi', 'Shankar', this.countries[0], 6445874544); submitted = false; onSubmit() { this.submitted = true; } active = true; newContact() { this.contact = new Contact('', ''); this.active = false; setTimeout(()=> this.active=true, 0); } }
導(dǎo)入NgForm,它提供CSS類和模型狀態(tài)。
templateUrl屬性提供了contact-form.component.html文件的路徑,其中包含我們的表單元素。
onSubmit()方法將在調(diào)用后將提交的值更改為true,newContact()將創(chuàng)建新的聯(lián)系人。
<div class="container"> <div [hidden]="submitted"> <h2>Contact Form</h2> <form *ngIf="active" (ngSubmit)="onSubmit()" #contactForm="ngForm" novalidate> <div class="form-group"> <label for="firstname">First Name</label> <input type="text" class="form-control" placeholder="Enter Your First Name" required [(ngModel)]="contact.firstname" ngControl="firstname" #firstname="ngForm" > <div [hidden]="firstname.valid || firstname.pristine" class="alert alert-danger"> firstname is required </div> </div> <div class="form-group"> <label for="lastname">Last Name</label> <input type="text" class="form-control" placeholder="Enter Your Last Name" [(ngModel)]="contact.lastname" ngControl="lastname" > </div> <div class="form-group"> <label for="country">Country</label> <select class="form-control" required [(ngModel)]="contact.country" ngControl="country" #country="ngForm" > <option value="" selected disabled>Select Your Country</option> <option *ngFor="#coun of countries" [value]="coun">{{coun}}</option> </select> <div [hidden]="country.valid || country.pristine" class="alert alert-danger"> Country is required </div> </div> <div class="form-group"> <label for="phone">Phone Number</label> <input type="number" class="form-control" placeholder="Enter Your Phone Number" [(ngModel)]="contact.phone" ngControl="phone" > </div> <button type="submit" class="btn btn-primary" [disabled]="!contactForm.form.valid">Submit</button> <button type="button" class="btn btn-primary" (click)="newContact()">New Contact</button> </form> </div> <div [hidden]="!submitted"> <h2>Your contact details :</h2> <div class="well"> <div class="row"> <div class="col-xs-2">First Name</div> <div class="col-xs-10 pull-left">{{ contact.firstname }}</div> </div> <div class="row"> <div class="col-xs-2">Last Name</div> <div class="col-xs-10 pull-left">{{ contact.lastname }}</div> </div> <div class="row"> <div class="col-xs-2">Country</div> <div class="col-xs-10 pull-left">{{ contact.country }}</div> </div> <div class="row"> <div class="col-xs-2">Phone Number</div> <div class="col-xs-10 pull-left">{{ contact.phone }}</div> </div> <br> <button class="btn btn-primary" (click)="submitted=false">Edit Contact</button> </div> </div> </div>
上面的代碼包含表單,在提交表單時(shí),ngSubmit指令調(diào)用onSubmit()方法。
當(dāng)提交的設(shè)置為false時(shí),顯示聯(lián)系人詳細(xì)信息。
它使用原始和有效的驗(yàn)證表單輸入元素。
ngIf指令檢查活動(dòng)對(duì)象是否設(shè)置為true以顯示表單。
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
將上面的HTML代碼保存為index.html文件,如同我們?cè)?a href="http://m.hgci.cn/Angular2/angular2_environment.html" target="_blank">環(huán)境章節(jié)中創(chuàng)建的,并使用上面的包含.ts文件的應(yīng)用程序文件夾。
打開(kāi)終端窗口并輸入以下命令:
npm start
稍后,瀏覽器選項(xiàng)卡應(yīng)打開(kāi)并顯示輸出,如下所示。
或者你可以用另一種方式運(yùn)行這個(gè)文件:
將以上HTML代碼作為angular2_forms.html文件保存在服務(wù)器根文件夾中。
將此HTML文件打開(kāi)為http://localhost/angular2_forms.html,并顯示如下所示的輸出。
更多建議: