【问题标题】:Angular *ngFor variable scope for event handlerAngular *ngFor 事件处理程序的变量范围
【发布时间】:2020-01-22 10:47:23
【问题描述】:

我刚开始学习 Angular,发现 ngFor 被放置在应该重复的子元素上,而不是父元素上(例如重复的元素列表)。

<select  class="form-control" id="sel {{order.product.id}}">
  <option (click)="this.unsetProductSize(order)" selected>Select size...</option>
  <option (click)="this.setProductSize(order, size.id, size.size, size.stock)" *ngFor="let size of order.product.productSize">{{size.size}}</option>
</select>

所以这里的问题是“点击”事件处理程序只能在 Firefox 上工作。这不是正确的方法,因为处理程序应该在选择元素(父)上,并且必须是“更改”事件处理程序。

如果我将函数移动到选择元素,来自 ngFor ("size") 的变量范围将超出范围。我需要为每个产品执行每个功能,因为我将有多个选择元素。我的问题是,有没有一种已知的方法来解决这个问题,或者可能是每个放置在父元素而不是子元素上的方法?

【问题讨论】:

  • 我觉得还有多余的空间
  • @NegiRox 是的,这是我的错,对不起。当我删除它时它没有显示效果。

标签: javascript html angular


【解决方案1】:

试试这个

<select  class="form-control" id="sel {{order.product.id}}" (change)="handleProductSizeChange($event)">
  <option [value]="null" selected>Select size...</option>
  <option [value]="size" *ngFor="let size of order.product.productSize">{{size.size}}</option>
</select>

每个选项都有一个值,并且在 select 元素处使用一个用于选项更改的处理程序

【讨论】:

  • 如何从传递给handleProductSizeChange($event)的事件中提取值(对象大小)?
  • $event.target.value 应该返回您所选选项的值
  • 我收到的 size 对象似乎是一个空对象,控制台将其记录为 [object Object]。当我尝试访问属性时,它显示未定义。
【解决方案2】:

这是[(ngModel)] 的完美用途。还可以使用[ngValue] 来捕获所选的整个对象。您也不需要函数unsetProductSize,因为您可以使用setProductSize 检查值是否存在。另外,不要在模板中使用this。总而言之,我建议如下:

<select [(ngModel)]="selectedSize" (ngModelChange)="setProductSize(order)">
  <option [ngValue]="null">Select size...</option>
  <option [ngValue]="size" *ngFor="let size of order.product.productSize">
    {{size.size}}
  </option>
</select>

TS:

selectedSize = null;

setProductSize(order) {
  console.log(order) // order here
  if (this.selectedSize) {
    // do stuff
  } else {
    // do other stuff!
  }
}

STACKBLITZ

【讨论】:

  • 谢谢。我使用您的解决方案让它工作。以这种方式使用角度更有意义。
【解决方案3】:

你可以和选择框上的点击事件。请参考以下代码

<select  class="form-control" (click)="setProductSize(order, $event.target.value)"  id="sel {{order.product.id}}">
  <option selected value="0">Select size...</option>
  <option  *ngFor="let size of order.product.productSize" [value]="size">{{size.size}}</option>
</select>

在 .ts 文件中,你可以编写你的功能

setProductSize(order, size){
//You have whole order object in order variable and selected size object in size variable
//if user click on Select size... option in size variable you will get the value 0. you can add condition according to the selected values
}

谢谢。

【讨论】:

  • 我收到的 size 对象似乎是一个空对象,控制台将其记录为 [object Object]。当我尝试访问属性时,它显示未定义。
  • 使用 JSON。 stringify() 打印对象
猜你喜欢
  • 1970-01-01
  • 2011-10-23
  • 2017-05-04
  • 1970-01-01
  • 2018-08-18
  • 2019-12-14
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
相关资源
最近更新 更多