Javascript function in Angular 10 not working

Viewed 901
3 Answers
<input type="text" id="myInput" (keyup)="search()" placeholder="Search for product.." title="Type in a name">

Use (keyup) instead of onkeyup.

According to your example would be better like this 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();
  }
}

You need to use (keyup) and I couldn't resist to review your code. Using document.getElement and so on is not the angular way of doing things. It can be done much easier. Please have a look at my Stackblitz: https://stackblitz.com/edit/angular-ivy-4bgobb?file=src/app/app.component.ts

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

I've added [(ngModel)] in your template and replaced your javascript with a filter function.

Related