[英]Observable event not working in Angular2
我試圖在angular2中創建一個Keyup事件,該事件在搜索框中鍵入內容時觸發,然后將該事件記錄在控制台中。 但是,控制台中什么也不會顯示。 這是我的app.component.ts文件
/// <reference path="../typings/tsd.d.ts" />
import {Component} from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'my-app',
template: `
<input id="search" type="text" class="form-control" placeholder="Search">
`
})
export class AppComponent {
constructor(){
var keyups = Observable.fromEvent($("#search"), "keyup");
keyups.subscribe(function(data) {
console.log(data);
});
}}
我的index.html文件是
<html>
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Latest compiled and minified CSS -->
<!--
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
-->
<link rel="stylesheet" href="app/bootstrap.min.css">
<link rel="stylesheet" href="app/styles.css">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
請有人指出我在這里缺少什么嗎? 謝謝
首先,您可以采用另一種方式來捕獲按鍵:
<input (keyup)="onKeyPress()" id="search" type="text" class="form-control" placeholder="Search">
這會將keyup
事件綁定到運行您分配給該事件綁定的內容。 然后,可以使用console.log
在組件中添加onKeyPress
函數。
https://angular.io/guide/template-syntax#event-binding
另一件事是,構造函數在初始化視圖之前運行。 因此,如果您堅持綁定到模板之外的事件,則可以執行以下操作:
export class AppComponent implements AfterViewInit
並在可以使用該Observable的組件中實現ngAfterViewInit
函數。 確保從@angular/core
導入AfterViewInit
。
您需要將事件綁定到輸入字段,然后將輸入字段綁定到對象,以成角度的方式進行。
HTML:
<input type="text" (keyup)="someFunction()" [(ngModel)]="model.name" />
然后在您的TS類支持中:
public model: Object = {};
public someFunction() {
console.log(model.name);
}
雙向綁定的角度將自動將輸入的值綁定到model.name
,並且(keyup)
事件將偵聽您想要的事件。
您尚未在構造函數中訪問DOM,因此實際上是在初始化該觀察程序以偵聽null
項目上的keyup
事件。 您需要做的是在ngAfterViewInit
生命周期掛鈎中初始化該觀察者。
ngAfterViewInit(){
var keyups = Observable.fromEvent($("#search"), "keyup");
keyups.subscribe(function(data) {
console.log(data);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.