I made a filter function, where the filter is applied to elements from a list, that works when i use it on the page with on click, like so
<button (click)="FilterFn5()"> do </button>
But it does not work when i put the function on ngOnInit. My ngOnInit looks like this:
ngOnInit(): void {
this.BuildingNameFilter="B"
this.BuildingRoomsFilter="2"
this.BuildingFloorFilter="0"
this.refreshBldList();
this.FilterFn5();
}
and the function is:
FilterFn5(){
var BuildingNameFilter = this.BuildingNameFilter;
var BuildingFloorFilter = this.BuildingFloorFilter;
var BuildingRoomsFilter = this.BuildingRoomsFilter;
this.BuildingList = this.BuildingListWithoutFilter.filter( (el:
{ BuildingId:
{ toString: () => string; }; BuildingFloor: { toString: () => string; };
BuildingName: { toString: () => string; }
ApartmentRooms: { toString: () => string; }; }) =>{
return el.ApartmentRooms.toString().toLowerCase().includes(
BuildingRoomsFilter.toString().trim().toLowerCase()
)
&& el.BuildingFloor.toString().toLowerCase().includes(
BuildingFloorFilter.toString().trim().toLowerCase()
)&&
el.BuildingName.toString().toLowerCase().includes(
BuildingNameFilter.toString().trim().toLowerCase()
)
});
}
The list that is filtered is BuildingList
and the function this.refreshBldList();
is where the list GET its elements
refreshBldList(){
this.service.getBuildingList().subscribe(data=>{
this.BuildingList=data;
this.BuildingListWithoutFilter=data;
});
}
CodePudding user response:
It's because of your async statement from your service get operation.
Basically, you are trying to call the FilterFn5() immediately after you call your service to retrieve the data. But your data might not be ready when you execute the FilterFn5 function.
I suggest to adapt your refresh function by:
ngOnInit(): void {
this.BuildingNameFilter="B"
this.BuildingRoomsFilter="2"
this.BuildingFloorFilter="0"
this.refreshBldList();
// this.FilterFn5(); <-- remove this line
}
// ...
refreshBldList(){
this.service.getBuildingList().subscribe(data=>{
this.BuildingList=data;
this.BuildingListWithoutFilter=data;
this.FilterFn5(); // <-- add this line
});
}
What you can also do is to disable your button in your HTML template until you've got the data from your service:
<button [disabled]="!BuildingListWithoutFilter" (click)="FilterFn5()"> do </button>