Angular 2 - (keyup)不起作用 - 英雄之旅

时间:2017-06-16 08:11:30

标签: angular

我做了一个英雄教程,在我的项目(keyup)活动中没有工作。

当我输入第一个字母时,angular发送请求并且在下一次按下之后没有发送。我在浏览器控制台中看到了请求的结果。

<div id="search-component">
<h4>Search products</h4>
<input #searchBox id="search-box" (keyup)="search(searchBox.value)"/>
<div>
    <div *ngFor="let product of products | async" (click)="gotoDetail(product)" class="search-result">
        {{product.name}}
    </div>
</div>

@Component({
    selector: 'product-search',
    templateUrl: './product-search.component.html',
    styleUrls: [ './product-search.component.css' ],
    providers: [ ProductSearchService ]
})
export class ProductSearchComponent implements OnInit {

    projects: Observable<Product[]>;
    private searchTerms = new Subject<string>();

    constructor(
        private productSearchService: ProductSearchService,
        private router: Router
    ) {}

    search(term: string): void {
        this.searchTerms.next(term);
    }

    ngOnInit(): void {
        this.products = this.searchTerms
            .debounceTime(300)
            .distinctUntilChanged()
            .switchMap(
                term => term ? 
                this.productSearchService.search(term) : 
                Observable.of<Product[]>([])
            )
            .catch(error => {
                console.log(error);
                return Observable.of<Product[]>([]);
            })
    }

    gotoDetail(product: Product): void {
        const link = ['/detail', product.id];
        this.router.navigate(link);
  }

}

2 个答案:

答案 0 :(得分:1)

因为您的searchBox变量实际上是您组件的ViewChild

请尝试使用此代码:

<input [(ngModel)]="searchBox" id="search-box" (keyup)="search(searchBox)"/>

答案 1 :(得分:1)

在你的html

中设置它

// HTML

<input [(ngModel)]="searchBox" id="search-box" (keyup)="search(event)"/>

// Compoenet

searchBox: string //在构造函数之前声明进入组件

//将构造函数声明到组件中

@HostListener('document:keyup', ['$event'])
    search(event: KeyboardEvent): void {
      this.searchTerms.next(this.searchBox);
    }