3 回答
TA贡献1788条经验 获得超4个赞
<input type="text" id="myInput" (keyup)="search()" placeholder="Search for product.." title="Type in a name">
使用(keyup)
而不是onkeyup
.
TA贡献1878条经验 获得超4个赞
根据你的例子会更好这样 app.component.html
<input
type="text"
id="myInput"
(keyup)="search($event.target)"
placeholder="Search for product.."
title="Type in a name"
/>
<ul id="myProduct" *ngFor="let product of filteredProducts">
<li>
<a href="#">{{ product.name }}</a>
</li>
</ul>
app.component.ts
import { Component, OnInit, VERSION } from '@angular/core';
import { Product } from './product';
import { ProductGroup } from './product-group';
import { ProductService } from './services/product.service';
// import * as var from 'jquery';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
constructor(private productService: ProductService) {}
product: Product[];
productGroup: ProductGroup[];
availableProducts: Product[];
filteredProducts: Product[];
search(e) {
this.filteredProducts = this.availableProducts.filter(
(p) => p.name.toUpperCase().indexOf(e.value.toUpperCase()) > -1
);
}
getProduct() {
this.productService.getProductsSmall().then((products) => {
this.availableProducts = products;
this.filteredProducts = products;
});
}
ngOnInit() {
this.getProduct();
}
}
TA贡献1946条经验 获得超4个赞
你需要使用(keyup)
,我忍不住要审查你的代码。使用 document.getElement 等并不是有角度的做事方式。这可以更容易完成。
<input type="text" id="myInput" (keyup)="search(searchTerm)" [(ngModel)]="searchTerm" placeholder="Search for product.." title="Type in a name">
<ul id="myProduct" *ngFor="let product of shownProducts">
<li><a href="#">{{product.name}}</a></li>
</ul>
constructor(private productService: ProductService) {}
product: Product[];
productGroup: ProductGroup[];
availableProducts: Product[];
shownProducts: Product[];
public searchTerm = "";
search(searchValue: string) {
this.shownProducts = this.availableProducts.filter((product: Product) => product.name.toLowerCase().includes(searchValue.toLowerCase()));
}
getProduct() {
this.productService
.getProductsSmall()
.then(products => ((this.availableProducts = products), this.search("")));
}
我已在您的模板中添加了[(ngModel)]并用过滤器函数替换了您的 javascript。
添加回答
举报