开发者

How to remove specific object from an array using service in angular 9

开发者 https://www.devze.com 2022-12-07 19:37 出处:网络
Trying to remove one object which name is Test1 from the array object. I do not know how to remove that.If i did anything wrong in my code you can correct it. I have used service to update the array v

Trying to remove one object which name is Test1 from the array object. I do not know how to remove that.If i did anything wrong in my code you can correct it. I have used service to update the array value. you 开发者_如何学运维can understand If you check my stackblitz. If i click the Remove Name button i want to remove the object which name is Test1 from the array object. So, Please help to find the solution.

dashboard.component.html:

<button (click)="callFun('Test1')">Remove Name</button> 
 {{ deleteItemName }}
<app-optymodel></app-optymodel>

dashboard.component.ts:

callFun(name: any) {
    this.commonService.modifyDeleteItem(name);
    this.commonService.modifyNameList(name);
    this.commonService.modifyDeleteItem('');
  }

common.service.ts:

 modifyNameList(name: string) {
 const nameList = this.nameList.getValue();
 const result = nameList.filter((x) => x.name != name); 
 this.nameList.next(result);
 }

 modifyDeleteItem(name: string) {
 this.deletedItem.next(name); 
 }

After cliked Remove Name button result it should be like

const result = nameList.filter((x) => x != name); console.log(result);

[ 
{ name: 'Test2', id: '2' },
{ name: 'Test3', id: '3' },
{ name: 'Test4', id: '4' },
{ name: 'Test5', id: '5' },
];

Demo: https://stackblitz.com/edit/angular-pass-table-data-to-input-property-zn22go?file=src%2Fapp%2Fservices%2Fcommon.service.ts


The code in your stackblitz is actually different than the one you showed here. The line

const result = nameList.filter((x) => x != name); 

should be

const result = nameList.filter((x) => x.name !== name); 

Then you will get an lint warning/compile error that the type is wrong because you have the name list defined as Array<string> while it actually should be Array<{name: string, id: string}>. I would recommend using a type or an interface for your content of the array.

And instead of Array.filter you could also use Array.splice if you just want to remove one item (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice?retiredLocale=de#remove_1_element_at_index_3)

0

精彩评论

暂无评论...
验证码 换一张
取 消