[英]mat-autocomplete selected mat-option pass multiple values from selectedItem
我有一个 mat-autocomplete,它加载 JSON 格式的表数据,当用户从自动完成中选择一个项目时,当前将单个 JSON 值映射为选定的“值”。
除了这个值之外,我还需要从这个选定项目的 JSON 节点传递一些其他值,因为这些值正在写入数据库。 所以我需要来自这个选定对象的 3 个值,而不仅仅是一个。
但我不确定如何从现有接口访问这些额外的 JSON 属性,或者我是否需要修改接口以允许传递这些值。
例如,填充自动完成的表数据如下,我们当前使用“codeFileType”作为用户从自动完成表中选择项目时传递的“值”:
"table-lookups": [
{
"codeFileType": "NEW_CODE_FILE_TYPE_A",
"datasource": "A",
"myAutoCompleteHook": "autocompleLookupTest1",
"myAutoCompleteParams": [
{
"name": "_endpoint",
"value": "MyCodeFile"
},
{
"name": "_labelKey",
"value": "code"
},
{
"name": "_valueKey",
"value": "description"
}
]
},
{
"codeFileType": "NEW_CODE_FILE_TYPE_B",
"datasource": "B",
"myAutoCompleteHook": "autocompleLookupTest2",
"myAutoCompleteParams": [
{
"name": "_endpoint",
"value": "MyCodeFile"
},
{
"name": "_labelKey",
"value": "code"
},
{
"name": "_valueKey",
"value": "description"
}
]
},
{
"codeFileType": "NEW_CODE_FILE_TYPE_C",
"datasource": "C",
"myAutoCompleteHook": "autocompleLookupTest3",
"myAutoCompleteParams": [
{
"name": "_endpoint",
"value": "MyCodeFile"
},
{
"name": "_labelKey",
"value": "code"
},
{
"name": "_valueKey",
"value": "description"
}
]
}
],
因此,从上面的 JSON 中,我们将codeFileType
映射为选择的“值”。 我还需要访问所选项目的“myAutoCompleteHook”和“myAutoCompleteParams”值,并将它们与 codeFileType 作为单独的数据点一起传递。
这是我们将 [value] 绑定到 valueKey 的 mat-option 元素的 HTML 格式:
<mat-option
*ngFor="let values of filteredResults$ | async; trackBy: trackByFn; index as i"
[value]="values[tableConfig?.valueKey]"
[innerHtml]="buildLabelFromValuesChecked(values, isOptionSelected(values[tableConfig?.valueKey]))">
</mat-option>
您可以只传递所选项目的index
,并使用index
号访问数组中的完整对象。 有史以来最简单的事情。
<mat-option
*ngFor="let values of filteredResults$ | async; trackBy: trackByFn; index as i"
[value]="i"
[innerHtml]="buildLabelFromValuesChecked(values, isOptionSelected(values[tableConfig?.valueKey]))">
</mat-option>
组件.ts:
// function that is assigned to mat-selected
someFunction(index: number) {
this.selectedItem = this.table-lookups[index]
}
我还看到您正在 filterResults filteredResults$
上运行*ngFor
。 如果 filtersResults filteredResults$
与table-lookups
不同,那么您可以将value
绑定到codeFileType
并使用findIndex
或filter
。
[value]="codeFileType"
组件.ts:
// function that is assigned to mat-selected
someFunction(value: string) {
// filter
this.selectedItem = this.table-lookups.filter((item) => item.codeFileType === value)[0] // since filter returns an array
}
// or findIndex
const itemIndex = this.table-lookups.findIndex((item) => item.codeFileType === value) // since filter returns an array
this.selectedItem = this.table-lookups[itemIndex];
}
然后你可以使用this.selectedItem.myAutoCompleteHook
和this.selectedItem.myAutoCompleteParams
来访问这些道具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.