I have a function called removePopUp. When I send an index sometimes I want to change whats inside that index in the array. Lets say I have an array of [0,1,2]. when I run removePopUp(1) that should return [0,2] there should be no 3rd element but the 3rd index would slide to the second element removing that element. The issue is its not displaying this activity in angularJs when I'm using a ngFor to display a child component.
messages.component.ts
...
userPopUpsArray : BookFaceMessage[] = []
...
removePopUp(index){
index = Number(index)
let usersLength = this.userPopUpsArray.length
if (usersLength === 3){
if (index === 1){
let thrid_index = this.userPopUpsArray[2]
this.userPopUpsArray[1] = thrid_index
}
else if(index === 0){
let second_index = this.userPopUpsArray[1]
let thrid_index = this.userPopUpsArray[2]
this.userPopUpsArray[0] = second_index
this.userPopUpsArray[1] = thrid_index
this.userPopUpsArray.pop()
}
else{
console.log(index)
this.userPopUpsArray.pop()
console.log(this.userPopUpsArray)
}
}
else if (usersLength === 2){
if(index === 0){
this.userPopUpsArray[0] = this.userPopUpsArray[1]
this.userPopUpsArray.pop()
}
else{
console.log(index)
this.userPopUpsArray.pop()
console.log(this.userPopUpsArray)
}
}
else{
this.userPopUpsArray.pop()
}
getPopUp(){
return this.userPopUpsArray
}
}
messages.component.html
...
<div *ngFor="let userPopUpData of userPopUpsArray; let i = index;trackBy: getPopUp">
<app-message-popup [userPopUpsArray]=userPopUpsArray [userPopUpData]=userPopUpData [removePopUp]=removePopUp [index]=i></app-message-popup>
...
</div>
If you need to remove the n-th element of an array you can use splice like this:
removePopUp(index) {
index = Number(index);
// check if provided index is number
if (isNaN(index)) {
return;
}
// check if provided index is within array length
if (index < 0 || this.userPopUpsArray.length <= index) {
return;
}
this.userPopUpsArray.splice(index, 1);
}
Note: it is a good idea to check if provided index is number, and also if its value is within array length. Keep in mind providing negative value to splice will start looking from the end of the array so both checks are necessary.