I'm trying to make a search box, which looks for product names and outputs product cards as a result. I have a MenuComponent which has the search input, and looks for the products in the database. (It holds for 300 ms so it does not have to make a request for each keystroke). getLikeName() returns products that have what is searched on its name.
search(searchInput: string){
if(this.interval != null){
clearInterval(this.interval);
}
this.interval = setTimeout(() => {
this.productHttpService.getLikeName(searchInput, 20).subscribe(
(products: any[]) => this.productContainer.displayProducts(products)
);
}, 300);
}
The displayProducts function updates the list of products. I have console.logged the result and effectively products are coming back. However the list is not updating on the website.
products: any[];
displayProducts(products: any[]){
this.products = products;
console.log(products);
}
This is the HTML file (I'm using Angular Material):
<md-grid-list cols="4" rowHeight="1:2" class="size">
<md-grid-tile *ngFor="let product of products" class="separation">
<md-card class="example-card">
<md-card-header>
<div md-card-avatar class="example-header-image"></div>
<md-card-title>${{product.price}}</md-card-title>
<md-card-subtitle>{{product.name}}</md-card-subtitle>
</md-card-header>
<img md-card-image [src]="product.imgUrl" style="width:300px; height:225px">
<md-card-content>
<p>
{{product.description}}
</p>
</md-card-content>
<md-card-actions>
<button md-button (click)="sidenav.open(); addToCart(product)">ADD TO CART</button>
</md-card-actions>
</md-card>
</md-grid-tile>
</md-grid-list>
Thank you in advance for your answer.
From the example code, it seems that the scope of the 'products' variable is limited to 'this.productContainer' and not 'this'. So the one getting updated is not the 'products' variable that is bound to the HTML.
The console.log would still work as you are printing it from inside the displayProducts() method.
Would be easier if you provide a plunker of your code.
If the display method is not doing anything other than display, I would suggest you change your code to the following:
this.interval = setTimeout(() => {
this.productHttpService.getLikeName(searchInput, 20).subscribe(
(products: any[]) => {this.products = products});
}, 300);
It looks like the products are located in productContainer.products. You can use . scoping inside the html, so change your html to read *ngFor="let product of productContainer.products".