用戶可以通過按鍵盤上的“Enter"鍵顯示輸入框的數(shù)據(jù)。
以下示例通過在Angular 2中使用鍵事件過濾來描述用戶輸入:
<!DOCTYPE html> <html> <head> <title>Angular 2 User Input Key Event Filtering</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/app/user_input_event_filtering') .then(null, console.error.bind(console)); </script> </head> <body> <event-filtering>Loading...</event-filtering> </body> </html>
上述代碼包括以下配置選項:
您可以使用 typescript 版本配置 index.html 文件。 在使用 transpiler 選項運行應(yīng)用程序之前,SystemJS將TypeScript轉(zhuǎn)換為JavaScript。
如果在運行應(yīng)用程序之前沒有翻譯到JavaScript,您可能會看到瀏覽器中隱藏的編譯器警告和錯誤。
當(dāng)設(shè)置了 emitDecoratorMetadata 選項時,TypeScript會為代碼的每個類生成元數(shù)據(jù)。 如果不指定此選項,將生成大量未使用的元數(shù)據(jù),這會影響文件大小和對應(yīng)用程序運行時的影響。
Angular 2包含來自 app 文件夾的包,其中文件將具有 .ts 擴展名。
接下來,它將從 app 文件夾加載主組件文件。 如果沒有找到主要組件文件,那么它將在控制臺中顯示錯誤。
當(dāng)Angular調(diào)用main.ts中的引導(dǎo)函數(shù)時,它讀取Component元數(shù)據(jù),找到“app"選擇器,定位一個名為app的元素標(biāo)簽,并在這些標(biāo)簽之間加載應(yīng)用程序。
要運行代碼,您需要在 app 文件夾下需要保存以下 TypeScript(.ts)文件。
user_input_event_filtering.tsimport {bootstrap} from 'angular2/platform/browser'; import {EventFilteringComponent} from "./event_filtering.component"; bootstrap(EventFilteringComponent);
現(xiàn)在我們將在TypeScript(.ts)文件中創(chuàng)建一個組件,如下所示:
event_filtering.component.tsimport {Component} from 'angular2/core'; @Component({ selector: 'event-filtering', template: ` <input #myval (keyup.enter)="values=myval.value"> <p>{{values}}</p> ` }) export class EventFilteringComponent { values=''; }
@Component 是一個裝飾器,它使用配置對象來創(chuàng)建組件及其視圖。
當(dāng)用戶按下鍵盤上的“Enter"鍵時,Angular 2調(diào)用 keyup 事件并顯示用戶輸入的文本。
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
將上述HTML代碼另存為 index.html 文件,如同我們在環(huán)境一章中創(chuàng)建的一樣,并使用上述 app i>文件夾,其中包含 .ts 文件。
打開終端窗口并輸入以下命令:
npm start
稍后,瀏覽器選項卡應(yīng)打開并顯示輸出,如下所示。
或者您可以以其他方式運行此文件:
將上述HTML代碼另存為服務(wù)器根文件夾中的 user_input_key_event_filtering.html 文件。
將此HTML文件打開為http://localhost/user_input_key_event_filtering.html,并顯示如下所示的輸出。
該示例通過在輸入框中輸入數(shù)據(jù)時按鍵盤上的“Enter"鍵顯示數(shù)據(jù)。
更多建議: