【问题标题】:angular 5: setting (click) value from an object not working角度 5:从不工作的对象设置(点击)值
【发布时间】:2018-09-24 20:04:22
【问题描述】:

我有一个导航菜单,它使用导航.ts json 文件呈现菜单项。当它到达 navitem 组件时,它使用 ngIf 来检查导航文件中的项目是否具有“功能”键,如果有,则所需的行为是使用对象中 item.function 中的字符串值来填充(单击)事件的值。

实际上,控制台会抛出一个错误,提示“_co.item.function is not a function”

HTML

<span class="nav-link" *ngIf="item.function" (click)="item.function()" matRipple>
    <mat-icon class="nav-link-icon" *ngIf="item.icon">{{item.icon}}</mat-icon>
    <span class="nav-link-title" [translate]="item.translate">{{item.title}}</span>
    <span class="nav-link-badge" *ngIf="item.badge" [translate]="item.badge.translate"
        [ngStyle]="{'background-color': item.badge.bg,'color': item.badge.fg}">
    {{item.badge.title}}
    </span>
</span>

导航.ts

      [{
"id": "accounting",
"title": "Accounting",
"type": "collapse",
"children": [
  {
    "id" : "salesmenSalesLocation",
    "title": "Salesmen Sales Location",
    "type": "item",
    "function": "handleSelect(ReportTypes.SalesmenSalesLocations)"
  },
  {
    "id": "laggingLedgerEntries",
    "title": "Lagging Ledger Entries",
    "type": "item",
    "function": "handleSelect(ReportTypes.LaggingLedgerEntries)"
  }
 ]}]

我也尝试过 (click)="item.function" 没有成功。

【问题讨论】:

  • 它可能是一个实际的函数,但就您的item.function 对象而言,它只是一个string,因此不是一个函数
  • 数据从何而来?你对源头有控制权吗?确实没有安全的方法来解析它。

标签: javascript angular typescript angular5


【解决方案1】:

我假设您可以在此处更改数据源,否则我看不到任何好的解决方案。

字符串不是函数,虽然你可以用eval 将它变成一个字符串,但这是一个坏主意。相反,您真正应该做的只是传递一个告诉函数使用什么的值。

将您的数据更改为以下内容:

{
  "id" : "salesmenSalesLocation",
  "title": "Salesmen Sales Location",
  "type": "item",
  "reportTypeSource": "SalesmenSalesLocations"
},
{
  "id": "laggingLedgerEntries",
  "title": "Lagging Ledger Entries",
  "type": "item",
  "reportTypeSource": "LaggingLedgerEntries"
}

然后将该值传递给您的函数并使用它来告诉它在哪里查找:

handleSelect (reportTypeSource: string) {
    const reportType = ReportTypes[reportTypeSource]
    // continue as before
}

然后在你的 HTML 中这样调用它:

(click)="handleSelect(item.reportTypeSource)"

【讨论】:

    【解决方案2】:

    问题出在这里:

    "function": "handleSelect(ReportTypes.LaggingLedgerEntries)"
    

    这里:

    (click)="item.function()"
    

    你不能简单地传递一个字符串并期望组件执行一个函数并且确切地知道要做什么。在这里你需要传递实际的函数。

    您的设置看起来过度配置。我会拆除配置并将逻辑放入组件本身。不要害怕拥有更多的模板,如果有什么能让事情更清晰(而不是配置)

    【讨论】:

      【解决方案3】:

      该功能存在于组件中还是仅存在于模型中?如果它只是在模型上,它将无法正常工作。 (单击)正在寻找组件上的方法。在这种情况下,它表面上只是一个字符串。

      【讨论】:

      • 是的,有一个函数handleSelect(reportType: number)
      • 在组件上?现在你正在传递一个字符串,传递实际的函数名。
      猜你喜欢
      • 2020-05-31
      • 1970-01-01
      • 2018-08-09
      • 2019-03-18
      • 1970-01-01
      • 2018-07-14
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多