Reputation: 11851
I have this method here:
messageSelected($event, index) {
console.log($event.target.checked);
console.log(index);
if ($event.target.checked) {
this.selectedMessages.push($event.target.getAttribute('name'));
}
else {
var item = this.selectedMessages.indexOf($event.target.getAttribute('name'), 0);
this.selectedMessages.slice(item, 1);
}
console.log(this.selectedMessages);
}
What I am trying to do is if an item is checked, add the item to the array (this part works) now I am trying to remove the item from the array if the checked is false (this part is not working)
The problem is that the item is not getting removed from the array. What am I doing wrong?
Here is my HTML:
<div class="card" *ngFor="let i of userMessages; let item = index">
<div class="card-body row-eq-height clearfix">
<div class="col-sm-2 vertical-center text-center">
<div class="avatar">
</div>
</div>
<div class="col-sm-8 vertical-center xs-center-text">
<strong class="username">Username</strong>
<p><a class="read-more" [routerLink]="['/singleMessage/' + i.id]">{{i.subject}}</a></p>
</div>
<div class="col-sm-2 col-xs-6 clearfix">
<span class="date">{{i.updated_at | date: 'MM/dd/yyyy'}}</span>
</div>
<div class="col-sm-1 col-xs-6 text-right clearfix no-x-padding">
<div class="custom-check pull-right">
<input type="checkbox" id="{{i.id}}" name="{{i.id}}" (change)="messageSelected($event, item)"/>
<label for="{{i.id}}"></label>
</div>
</div>
</div>
</div>
Upvotes: 2
Views: 188
Reputation: 841
Besides the confusion between slice
(not mutating option) and splice
, it seems like you're using angular as vanilla js.
The whole idea of using a framework like this, is to get rid of DOM inspection / manipulation.
You don't need to overload the <input name>
, you could call directly messageSelected($event.target.checked, i.id)
(modifying the function firm as well, providing all the needed data).
Better than that, you could use two way binding [(ngModel)]="selectedItems[i.id]"
to bind the checkbox
to a map (object) of "selected items", and then simply extract the true
entries, mapping this to an array.
Or, if you dont mind to mutate the i
object, you could bind ngModel
directly on a custom property like [(ngModel)]="i.selected"
.
The idea is to avoid wiring manually the change
and the getAttribute('name')
.
Here's a living example: https://codesandbox.io/s/rjxn1y84wm
Upvotes: 1
Reputation: 17719
AngularJS binds to the Array Object, and the slice function in JS creates a new array as a result, leaving the original array as it is.
You should use splice (note the p) which will update the array.
For example:
var index = this.selectedMessages.indexOf($event.target.getAttribute('name'));
this.selectedMessages.splice(index, 1);
Upvotes: 1