简体   繁体   English

NgIf, async pipe 'as' 并为局部变量分配新值

[英]NgIf, async pipe 'as' and assigning new value to the local variable

Straight to the code since the question is probably unclear.直接进入代码,因为问题可能不清楚。

Template:模板:

<ng-container *ngIf="attributes$ | async as attributes">
  <div *ngFor="let attribute of attributes; let i = index">
    <input [(ngModel)]="attribute.key" [name]="'attribute-key' + i">
    <button (click)="deleteAttribute(attributes, attribute.key)"></button>
  </div>
</ng-container>

Code behind:后面的代码:

deleteAttribute(attributes: EquipmentAttribute[], key: string) {
  console.log(attributes);
  attributes = attributes.filter(x => x.key != key)
  console.log(attributes);
}

Lets say the array has 2 elements.假设数组有 2 个元素。 First console.log outputs [first, second] .第一个 console.log 输出[first, second] Second console.log outputs [first] .第二个 console.log 输出[first] Template still shows 2 elements.模板仍然显示 2 个元素。 If I click again on the button, I get the same result.如果我再次单击该按钮,我会得到相同的结果。

Why is that so?为什么呢? Is attributes passed as a copy? attributes是否作为副本传递? If I subscribe to the observable and assign the result in the code behind instead of using the async pipe, everything works.如果我订阅 observable 并在后面的代码中分配结果而不是使用异步 pipe,那么一切正常。

What's weird is that if I use attributes.splice(0, 1), changes are reflected in the template.奇怪的是,如果我使用 attributes.splice(0, 1),更改会反映在模板中。 I'm really confused.我真的很困惑。

Can anyone explain how this works?谁能解释这是如何工作的?

filter returns a new array, and when you assign it back to 'attributes', it gets lost when the function ends filter返回一个新数组,当您将其分配回“属性”时,它会在 function 结束时丢失

splice works because you are splicing the array 'attributes' is pointing TO. splice 有效,因为您正在拼接数组“属性”指向 TO。

To accomplish what you want cleanly, you have to tell whatever the source of the attributes$ observable, that a delete happened.为了干净地完成你想要的,你必须告诉attributes$ observable的任何来源,删除发生了。

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

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