Angular 10 中的 Javascript 函数不起作用

我使用 JavaScript 创建了简单的代码来过滤 Angular 10 中产品的数据。但是 html 中的 onkeyup 无法识别 typescript 中的搜索功能。可能是什么问题呢?

梵蒂冈之花
浏览 122回答 3
3回答

尚方宝剑之说

<input&nbsp;type="text"&nbsp;id="myInput"&nbsp;(keyup)="search()"&nbsp;placeholder="Search&nbsp;for&nbsp;product.."&nbsp;title="Type&nbsp;in&nbsp;a&nbsp;name">使用(keyup)而不是onkeyup.

UYOU

根据你的例子会更好这样 app.component.html<input&nbsp; type="text"&nbsp; id="myInput"&nbsp; (keyup)="search($event.target)"&nbsp; placeholder="Search for product.."&nbsp; title="Type in a name"/><ul id="myProduct" *ngFor="let product of filteredProducts">&nbsp; <li>&nbsp; &nbsp; <a href="#">{{ product.name }}</a>&nbsp; </li></ul>app.component.tsimport { 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({&nbsp; selector: 'my-app',&nbsp; templateUrl: './app.component.html',&nbsp; styleUrls: ['./app.component.css'],})export class AppComponent implements OnInit {&nbsp; constructor(private productService: ProductService) {}&nbsp; product: Product[];&nbsp; productGroup: ProductGroup[];&nbsp; availableProducts: Product[];&nbsp; filteredProducts: Product[];&nbsp; search(e) {&nbsp; &nbsp; this.filteredProducts = this.availableProducts.filter(&nbsp; &nbsp; &nbsp; (p) => p.name.toUpperCase().indexOf(e.value.toUpperCase()) > -1&nbsp; &nbsp; );&nbsp; }&nbsp; getProduct() {&nbsp; &nbsp; this.productService.getProductsSmall().then((products) => {&nbsp; &nbsp; &nbsp; this.availableProducts = products;&nbsp; &nbsp; &nbsp; this.filteredProducts = products;&nbsp; &nbsp; });&nbsp; }&nbsp; ngOnInit() {&nbsp; &nbsp; this.getProduct();&nbsp; }}

绝地无双

你需要使用(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。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript