I'm currently facing an issue with a specific part of the application I'm developing:
This is how the component's logic works:
export class StockStatusComponent implements OnInit{
articles: Article[] = [];
selectedLevel: any;
constructor(private service: ArticleService) {
}
ngOnInit(): void {
this.loadDataFromBackend();
}
loadDataFromBackend() {
this.service.getArticles().subscribe(res => {
for (let i = 0; i < res.length; i++) {
let actualStock = res[i].stockActual;
let minimumStock = res[i].stockMinimo;
if (actualStock < minimumStock) {
this.articles.push(res[i]);
}
}
})
console.log(this.articles);
}
filterByLevels(event: any) {
const level = event.target.value;
this.selectedLevel = level;
}
selectLevel() {
console.log("Selected level: " + this.selectedLevel);
if (this.selectedLevel === "all") {
this.service.getArticles().subscribe(res => {
this.articles = res;
})
}
console.log(this.articles);
}
}
HTML:
<div>
<div>
<label>Filter by Stock Levels</label>
<select (change)="filterByLevels($event)">
<option value=""></option>
<option value="all">All</option>
</select>
<button class="btn btn-success" (click)="selectLevel()">Select</button>
</div>
</div>
Explanation of the code steps:
Upon accessing the component, it should display in the console the "articles" that meet the specified condition. This part seems to be working correctly as it fetches the desired data in the ngOnInit function.
The issue arises when I select an option from the list, such as 'all'. It should fetch all articles, but it only does so after clicking twice. Here's an example to illustrate:
Example:
When entering the component, the array is empty due to no records meeting the condition at that moment.
Selecting the 'all' option should display all records, however, it initially shows the same result as in step 1. To get the desired outcome, I need to click again and re-execute the 'select Level()' method.
I appreciate any assistance provided in advance!