简体   繁体   English

通过从 HTML 传递来更改 Angular 组件的变量

[英]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:我正在开发一个 Angular (8) 应用程序,我有一个项目列表,我在 HTML 中使用 *ngFor 进行迭代,如下所示:

        <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.我想要做的是使用 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:这是我的 function 的样子:

  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).如您所见,我将列表作为参数传递给此 function(而不是从我现在所在的组件访问列表)。 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.我这样做是因为我想调用这个 function 来对我在同一个文件中拥有的另一个列表进行另一个删除操作,所以我不仅要知道要删除哪个元素,还要知道从哪个列表中删除。

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.问题是从 HTML 传递列表并更改该参数列表变量不会更改我正在迭代的组件的实际变量。 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. Standby954的回答解决了我的问题。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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