patternjavascriptangularCritical
remove item from stored array in angular 2
Viewed 0 times
angulararrayfromstoredremoveitem
Problem
I want to remove an item from a stored array in angular 2, with Type Script. I am using a service called Data Service, the DataService Code:
And my component class:
Now, everything is working good except when I try to delete an item. The log shows me that the item is still in the array, and therefore is still shown on the page. How can I remove the item after selecting it with the delete button??
export class DataService {
private data: string[] = [];
addData(msg: string) {
this.data.push(msg);
}
getData() {
return this.data;
}
deleteMsg(msg: string) {
delete [this.data.indexOf(msg)];
}
}And my component class:
import {Component} from '@angular/core'
import {LogService} from './log.service'
import {DataService} from './data.service'
@Component({
selector: 'tests',
template:
`
Testing Component
log
store
send
Show Storage
log array
{{item}}
Delete
{{value}}
`
})
export class TestsComponent {
items: string[] = [];
constructor(
private logService: LogService,
private dataService: DataService) {
}
logM(message: string) {
this.logService.WriteToLog(message);
}
store(message: string) {
this.dataService.addData(message);
}
send(message: string) {
}
show() {
this.items = this.dataService.getData();
}
deleteItem(message: string) {
this.dataService.deleteMsg(message);
}
logarray() {
this.logService.WriteToLog(this.items.toString());
}
}Now, everything is working good except when I try to delete an item. The log shows me that the item is still in the array, and therefore is still shown on the page. How can I remove the item after selecting it with the delete button??
Solution
You can't use
You should use splice to remove an element from an array:
delete to remove an item from an array. This is only used to remove a property from an object.You should use splice to remove an element from an array:
deleteMsg(msg:string) {
const index: number = this.data.indexOf(msg);
if (index !== -1) {
this.data.splice(index, 1);
}
}Code Snippets
deleteMsg(msg:string) {
const index: number = this.data.indexOf(msg);
if (index !== -1) {
this.data.splice(index, 1);
}
}Context
Stack Overflow Q#40462369, score: 295
Revisions (0)
No revisions yet.