user
user

Reputation: 4830

Angular 2 - (keyup) doesn't work - Tour of heroes

I do a tutorial tour of heroes and in my project (keyup) event doesn't work.

When I input first letter angular is sending a request and after the next presses is not sending. I see the results of requests in browser console.

<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);
  }

}

Upvotes: 0

Views: 362

Answers (2)

Shailesh Ladumor
Shailesh Ladumor

Reputation: 7242

set this like in your html

// HTML

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

// Compoenet

searchBox: string // declare before constructor into your component

// declare after constructor into your component

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

Upvotes: 1

user4676340
user4676340

Reputation:

Because your searchBox variable is actually a ViewChild of your component.

Try using this instead :

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

Upvotes: 1

Related Questions