简体   繁体   中英

Change an Angular component's variable by passing it from the HTML

I'm working on an Angular (8) application and I have a list of items which I iterate using *ngFor in the HTML like this:

        <div *ngFor="let item of someList">
          <app-template [item]="item"
                        (deleteItem)="deleteFromList($event, someList)"></app-template>
        </div>

What I want to do is to delete one item from the list using the deleteFromList() function. I have found a method for delete that I quite like, but other alternatives can be presented. Here is how my function looks like:

  deleteFromList(forDeletion, myList) {
      myList = myList.filter(item => item !== forDeletion);                 
  }

As you see, I am passing the list as a parameter to this function (instead of accessing the list from the component where I am now). I do this because I want to call this function for another delete operation for another list that I have in the same file, so I must know not only which element to delete, but from which of the lists.

The problem is that passing the list from HTML and change that parameter list variable will not change the actual variable from the component which I am iterating on. Is there a clean and ethical solution to this? And why isn't that list variable changing if I change the param list variable ?

Thank you: :)

standby954's answer solved my problem. Seems that I can not reasign the list passed as a param but only to modify it. Solution:

const el = myList.findIndex(item => item.id === forDeletion);
myList.splice(el, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM