您可以通過在頁面上的輸入框之外單擊鼠標(biāo)使輸入框失去焦點(diǎn)。
下面的例子描述了在Angular 2中的用戶對(duì)blur事件的輸入:
<!DOCTYPE html> <html> <head> <title>Angular 2 User Input On Blur</title> <script src="/attachments/w3c/es6-shim.min.js"></script> <script src="/attachments/w3c/system-polyfills.js"></script> <script src="/attachments/w3c/angular2-polyfills.js"></script> <script src="/attachments/w3c/system.js"></script> <script src="/attachments/w3c/typescript.js"></script> <script src="/attachments/w3c/Rx.js"></script> <script src="/attachments/w3c/angular2.dev.js"></script> <script> System.config({ transpiler: 'typescript', typescriptOptions: { emitDecoratorMetadata: true }, packages: {'app': {defaultExtension: 'ts'}} }); System.import('/angular2/src/pp/user_input_onblur_event') .then(null, console.error.bind(console)); </script> </head> <body> <onblur-event>Loading...</onblur-event> </body> </html>
上述代碼包括以下配置選項(xiàng):
您可以使用typescript版本配置index.html文件。在使用transpiler選項(xiàng)運(yùn)行應(yīng)用程序之前,SystemJS將TypeScript轉(zhuǎn)換為JavaScript。
如果在運(yùn)行應(yīng)用程序之前沒有翻譯到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包括來自app文件夾的包,其中文件將具有.ts擴(kuò)展名。
接下來它將從應(yīng)用程序文件夾加載主組件文件。如果沒有找到主要組件文件,那么它將在控制臺(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)用程序文件夾下。
user_input_onblur_event.tsimport {bootstrap} from 'angular2/platform/browser'; import {OnblurEventComponent} from "./user_onblur_event.component"; bootstrap(OnblurEventComponent);
現(xiàn)在我們將在TypeScript(.ts)文件中創(chuàng)建一個(gè)組件,如下所示:
user_onblur_event.component.tsimport {Component} from 'angular2/core'; @Component({ selector: 'onblur-event', template: `<h2>User Input On Blur Event</h2> <input #myval (keyup.enter)="values=myval.value" (blur)="values=myval.value"> <p>{{values}}</p> ` }) export class OnblurEventComponent { values=''; }
@Component是一個(gè)裝飾器,它使用配置對(duì)象來創(chuàng)建組件及其視圖。
當(dāng)用戶離開表單字段時(shí),Angular 2調(diào)用keyup事件,onblur事件使輸入框失去焦點(diǎn)。
讓我們執(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)用程序文件夾。
打開終端窗口并輸入以下命令:
npm start
稍后,瀏覽器選項(xiàng)卡應(yīng)打開并顯示輸出,如下所示。
或者你可以用另一種方式運(yùn)行這個(gè)文件:
將上述HTML代碼作為 user_input_onblur.html 文件保存在服務(wù)器根文件夾中。
將此HTML文件打開為http://localhost/user_input_onblur.html,并顯示如下所示的輸出。
該示例顯示了當(dāng)用戶離開表單字段并使輸入框失去焦點(diǎn)時(shí)onblur事件的功能。
更多建議: