I want to search in my table but I want the table to be filled with my data to start with. Currently, it will only be filled once I start typing in the search bar.
I think the problem is coming from that the productsArray is empty when the component is initialized
My data is coming from a JSON file in the project.
Below you can see what I currently have
export class TableComponent implements OnInit {
searchText: any;
productsArray: Products[] = [];
filteredArray = [...this.productsArray];
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.getProducts().subscribe((res) => {
this.productsArray = res;
});
}
getProducts(): Observable < Products[] > {
return this.http
.get < any > ('assets/mock.data.json')
.pipe(map((results) => results.data));
}
filterArray(): any {
if (!this.productsArray.length) {
this.filteredArray = [];
return;
}
if (!this.searchText) {
this.filteredArray = [...this.productsArray];
return;
}
const products = [...this.productsArray];
const properties = Object.keys(products[0]);
this.filteredArray = products.filter((product) => {
return properties.find((property) => {
const valueString = product[property].toString().toLowerCase();
return valueString.includes(this.searchText.toLowerCase());
}) ?
product :
null;
});
}
}
Code
Name
Category
<tbody *ngFor="let product of filteredArray; let i = index">
<tr>
<td>{{ product.code }}</td>
<td>{{ product.name }}</td>
<td>{{ product.category }}</td>
</tr>
</tbody>
filterArrayalso within the subscription callback after you assignedthis.productsArrayto apply an initial filter.