【问题标题】:Why doesn't my ngIf condition function work?为什么我的 ngIf 条件函数不起作用?
【发布时间】:2021-12-19 21:35:09
【问题描述】:

我正在尝试执行一个条件:如果来自数据矩阵的数据是 = "Inversión" 你必须为我输入一个值,如果它是 = "Funcionamiento" 你必须输入另一个值,如果有什么都不是,是因为有错误!这里我留下部分代码。

HTML:

<tr *ngFor="let dato of dataRoute">
  <td mat-cell colspan="2" *ngIf="recurso(dato.tipoGasto)" style="text-align: center; vertical- 
  align: middle;">
           {{recurso(dato.tipoGasto)}}
  </td>
</tr>

TS:

recurso() {
    if(this.dataRoute.tipoGasto == "Inversión"){
      return "[10] RECURSOS CORRIENTES"
    }
    if(this.dataRoute.tipoGasto == "Funcionamiento"){
      return "[11] OTROS RECURSOS DEL TESORO"
    }
    else {
      return " Error! "
    }
  }

总是收到“错误!”。我进行了调试,在 this.dataRoute 中有数据,但是在 this.dataRoute.tipoGasto 中什么都没有,它显示为“未定义”。

非常感谢您的帮助!

【问题讨论】:

  • 你试图从标记传递给函数什么?您的函数定义没有任何参数。您应该传递一个值或使用状态数据,但不能同时使用两者。
  • *ngIf 只是获取布尔类型而不是字符串!

标签: html angular typescript angular-material conditional-statements


【解决方案1】:
  1. *ngIf 的工作方式与您的目标略有不同。因此你的函数总是返回一个字符串,不管是什么字符串,它都会被转换成true

  2. 您的 recurso 函数不接受任何参数 - 这是另一个问题。

ngSwitch 和一些代码更新可以更好地解决您想要实现的目标。

<tr *ngFor="let dato of dataRoute">
  <ng-container [ngSwitch]="recurso(dato.tipoGasto)">
    <td mat-cell colspan="2" *ngSwitchCase="'[10] RECURSOS CORRIENTES'">{{recurso(dato.tipoGasto)}}</td>
    <td mat-cell colspan="2" *ngSwitchCase="'[11] OTROS RECURSOS DEL TESORO'">{{recurso(dato.tipoGasto)}}</td>
  </ng-container>
</tr>

但因此你总是循环选择你的选项,值得仔细检查你的逻辑。其他解决方案,只是简单地输出计算值。

<tr>
    <td mat-cell colspan="2">{{recurso(dataRoute.tipoGasto)}}</td>
</tr>

希望这对您有所帮助,但如果您有任何其他问题,请发表评论。我的其他建议是:

  1. 始终使用英语进行编程 - 这是通用语言,如果您必须在 StakcOverflow 上提问,找到会回答的人要容易得多。
  2. 在您的 ngSwitch 案例中不依赖像 [10] RECURSOS CORRIENTES 这样的值 - 使用更简单的值。

编辑

如果您正在循环访问 dataRoute 数据集,如果 Angular 开箱即用地处理这四个您,它必须是 Array 类型。您根本无法从中读取this.dataRoute.tipoGasto。它返回 undefined 然后总是最后一个 else 分支将为您返回。所以第一个问题是你的函数的if 语句。

【讨论】:

  • 感谢您的回答@vazsonyidl!确实我的dataRoutearray,那么我该如何从 TS 中解决我的问题呢?
猜你喜欢
  • 2018-07-21
  • 2015-02-28
  • 2011-12-20
  • 2020-11-16
  • 2021-03-21
  • 2021-12-18
  • 2011-06-23
  • 1970-01-01
相关资源
最近更新 更多