【问题标题】:how to Dynamically generate different variables in Angular?如何在 Angular 中动态生成不同的变量?
【发布时间】:2020-07-17 16:48:36
【问题描述】:

我选择了两个复选框,金额在第一个 div 的 Total Claimed 中计算,但第二个 div 的金额也在计算。我知道的原因;因为 div 是使用数组创建的,而我有一个公共变量。现在问题来了,如何创建动态变量?

在下面的代码中,您会发现 {{claimed}} 这是公共变量,我需要它是动态的:

<p>Total Claimed: [<span [ngClass]="{'text-success': claimed <= d.program_max_limit, 'text-warning': claimed > d.program_max_limit}">{{claimed | number : '2.'}}&nbsp;</span> Of {{d.program_max_limit | number : '2.'}}]</p>

component.ts 这是计算部分的功能:

  calc(event,val, id) {
    console.log(val,id)
    var i=0;
    if(id == event.target.value){
       if(event.target.checked ){ 
        this.claimed = parseInt(this.claimed) + parseInt(val);
        if (this.claimed > this.max_amount) {
          this.push.showError("You Have Reached the Maximum Limit");
          this.isDisabled = true;
          this.checkForm.reset();
          this.claimed = 0;
        } else {
          this.isDisabled = false;
        }
      } else {
        this.claimed = parseInt(this.claimed) - parseInt(val);
      }

    }

【问题讨论】:

  • 这个还在等待中吗?
  • @GouravGarg 没有。答案是Eliseo给出的,但无论如何都比x

标签: javascript arrays angular multidimensional-array dynamic


【解决方案1】:

定义一个布尔变量类型数组并在表中使用。

check:boolean[]=[]; //<--see that you equal to an array

我想你有一些喜欢

<tr *ngFor="let item of listItems;let i=index">
<td>{{item.invoiceAmmount}}</td>
...
<td><input type="checkbox" [(ngModel)]="check[i]"></td>
</tr>

然后你可以使用 getter 来总计

get total()
{
   let total=0;
   this.listItems.forEach((x,index)=>{
     if (check[index])
         total+=x.invoiceAmmount;
   })
   return total;
}

在你的 .html 中

Total:{{total}}
<div *ngIf="total>max_ammount">You has execeded tha ammout!</div>

注意:如果你不想使用 getter,你可以使用

<td><input type="checkbox" [ngModel]="check[i]"
                           (ngModelChange)="check[i]=$event;getTotal()">
</td>

getTotal()  //<--your function getTotal
{
       let total=0;
       this.listItems.forEach((x,index)=>{
         if (check[index])
             total+=x.invoiceAmmount;
       })
       this.total=total //<--store the total in a variable "total"
}

【讨论】:

  • 感谢您的回答。我已经应用了它,但是如果用户检查[0],它会同时在两个框中进行检查
  • 第一行是check[0],第二行是check[1],第三行是check[2],看使用;let i=index[ngModel]="check[i]"
  • 我同意,但没有第三个复选框,等一下,我会告诉你我的架构。我会编辑我的答案
  • 当然,你有这么多的“检查”作为行数有你的表
  • 我已经编辑了答案并感谢您的努力。我真的很感激
猜你喜欢
  • 2018-02-13
  • 2021-08-29
  • 2022-08-04
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 2019-07-03
  • 2012-06-04
相关资源
最近更新 更多