javascript - angular 5:从对象设置 (click) 值不工作
我有一个导航菜单,它是使用 navigation.ts 的 JSON 文件来渲染菜单项的。当它到达 navitem 组件时,它使用 ngIf 来检查导航文件中的项是否有一个“function”键,如果有,期望的行为是使用对象中 item.function 的字符串值来填充 (click) 事件的值。
实际上,控制台抛出一个错误,说“_co.item.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",但没有成功。
答案#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()"
你不能简单地传递一个字符串并期望组件执行一个函数并且也能准确地知道该做什么。在这里,你需要传递实际的函数。
你的设置看起来配置过度了。我会拆掉配置,把逻辑放到组件本身。也不要害怕使用更多模板,如果有的话,这实际上会让事情更易读(相比配置而言)。
