typescript - Angular 4 - Wert aus Array entfernen, wenn das Kontrollkästchen deaktiviert wird
Wie kann ich den Wert aus dem Array entfernen, wenn ich das Kontrollkästchen deaktiviere?
html
<input type="checkbox" id="saveUserNameCheckBox" (change)="selChk(member.id)" [checked]="false">
Komponente
selChk(val) {
if (this.id.indexOf(val) == -1) {
this.id.push(val);
console.log(this.id);
}
}
Antwort #1
Du hast den Index bereits gefunden, warum dann nicht einfach splice verwenden?
selChk(val) {
var index = this.id.indexOf(val);
if(index === -1){
// val not found, pushing onto array
this.id.push(val);
}else{
// val is found, removing from array
this.id.splice(index,1);
}
}
Antwort #2
Ihr HTML :
<input (change)="onCheckUser(user.user_id,$event)" type="checkbox">
In deinen Ts:
Follow_list = []; // Variable Declared
onCheckUser(Id, event) {
const checked = event.target.checked; // stored checked value true or false
if (checked) {
this.Follow_list.push({ user_id: Id }); // push the Id in array if checked
} else {
const index = this.Follow_list.findIndex(list => list.user_id == Id);//Find the index of stored id
this.Follow_list.splice(index, 1); // Then remove
}
}
