i'm trying to share a list of selected items from a component to an other one. i created a service to declare the list :
public selectedTasksToUnassign = [];
then in this component i try to set the list values:
component_1.ts
checkTask(task) {
if (task) {
if (this.selectedTasks.includes(task)) {
this.selectedTasks.splice(this.selectedTasks.indexOf(task), 1);
} else {
this.selectedTasks.push(task);
}
} else {
if (this.selectedTasks.length < this.tasks.length) {
this.selectedTasks = [];
Array.prototype.push.apply(this.selectedTasks, this.tasks);
} else {
this.selectedTasks = [];
}
}
this.tasksToSelect.emit(this.selectedTasks);
this.formService.selectedTasksToUnassign=this.selectedTasks;
console.log("task to unassign from table", this.formService.selectedTasksToUnassign);
}
and in this component i want to get the list : component_2.ts
ngOnInit() {
console.log("test tasks to unassign",this.formService.selectedTasksToUnassign);
}
in fact im seeing that everytime i check an item in my table the liste is updated in the console.log in component_1.ts and im seeying the values are added but in the console.log in component_2.ts , it shows me only the first value selected !!!
That's because (I'm assuming) you're invoking
checkTask()each time you interact with the task list. BecausecheckTask()includes theconsole.log, you're seeing it with every interaction in component_1.However, on component_2 you have a
console.logon thengOnInit()which runs only once when the component is loaded. That's why you only see the firstconsole.log.If you bind
formService.selectedTaskToUnassignto component_2's template, you will see that it updates every time component_1 mutates its value.component_2.component.ts
component_2.component.html