I have a simple select all and select one item. The error happens when selectAll is clicked then selectone is clicked next. The original list also gets deleted. What can I do to solve this? Any help is appreciated.
TS code:
original$: BehaviorSubject<SomeObject[]> = new BehaviorSubject<SomeObject[]>([]);
selected$: BehaviorSubject<SomeObject[]> = new BehaviorSubject<SomeObject[]>([]);
selectAll(event)
{
if(event.target.checked){
this.selected$.next(this.original$.value);
}
else{
this.selected$ = new BehaviorSubject<SomeObject[]>([]);
}
}
selectone(event, obj) {
let list = this.selected$.value;
if (event.target.checked) {
list.push(obj);
}
else {
//error is here, even item in orginal$ is removed
_.remove(list, x => x.id == obj.id);
}
this.selected$.next(list);
}
HTML code:
<input id="select All" type="checkbox" (change)="selectAll($event)">
<tr *ngFor="let x of original$ | async; let index = index">
<input id="{{ index }}" type="checkbox" (change)="selectone($event, x)" />
</tr>
CodePudding user response:
Problem
Due to behavior subjects storing array values:
this.selected$.next(this.original$.value)
assigns the same array pointer to both behavior subjects.
Solution:
Instead, do
this.selected$.next([...this.original$.value])
which assigns selected$ a copy of original$