javascript - 有什么方法可以将 json 键作为字符串 @Input() 以角度传递
问题描述
我正在尝试使用角度材料自动完成来创建自定义组件,这样我就可以在我的代码中的任何地方使用它,因为我正在传递动态数组,并且对于每个数组,都有不同的键我卡在一个点上。
我尝试的是
app.component.html
<app-autocomplete [items]="data.attributes" [field]="'caption.default'" inputType="text" inputPlaceholder="placeholder"></app-autocomplete>
自动完成组件.ts
var str1="";
var length= this.field.split(".");
str1= "'"+length[0]+"']";
console.log(length.length)
for(var i=1;i<length.length;i++){
if(i===length.length-1){
str1= str1+"['"+length[i];
}else{
str1= str1+"['"+length[i]+"']";
}
}
this.field=str1;
console.log(this.field);
所以它会返回我 ['abc']['xyz']
autocomplete.component.html
<mat-form-field class="example-full-width">
<input type="{{inputType}}" placeholder="{{inputPlaceholder}}" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of items " [value]="option">
{{option[field]}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
我也尝试使用“.”,例如:“caption.default”
它不起作用,任何人都可以帮我解决这个问题......!!!
我正在尝试使我的组件通用,所以我可以在任何地方使用只需填写一些数据@Inputs,就像我有两个 json
JSON-1
[{
"caption": {
"default": "Asset ID"
}
},
{
"caption": {
"default": "Asset ID"
}
}]
我的第二个 json 是 JSON-2
[{
"name": {
"anything": "Asset ID"
}
},
{
"name": {
"anything": "Asset ID"
}
}]
所以对于我的第一个 json-1,我会这样使用
<app-autocomplete [items]="data.attributes" [field]="'caption.default'" inputType="text" inputPlaceholder="placeholder"></app-autocomplete>
对于第二个 json-2,我会这样使用
<app-autocomplete [items]="data.attributes" [field]="'name.anything'" inputType="text" inputPlaceholder="placeholder"></app-autocomplete>
意味着我想传递字段,以便它可以自动遍历并向我显示数据
解决方案
简单的解决方案,但请进一步阅读以了解哪里出了问题
改变
this.fields = field.split(".");
{{option[field]}} ---> {{option[fields[0]][fields[1]]}}
让我简化一下,
您基本上是在尝试访问作为数组一部分的对象的内部属性,因此尝试传递字段数据并直接获取它,
关于它应该是的项目
items[index][ObjectAttr][innerObjAttr]
对于您的示例 JSON1,它应该是
`items[index][caption][default]`
但你正在做的是
items[index][[caption][default]]
这是行不通的
推荐阅读
- xml - 将 XML 数据从基于 Web 的源导入 Google 表格
- r - 检查函数中的字符条目是否在 R 中的向量集中
- sql-server - 购买商品并在 SQL Server 中保存供应商的名称
- python - DecisionTreeClassifier 中两片叶子之间的距离
- powershell - 在几个路径中递归地计算文件,在 Powershell 中排除和消除冗余文件
- azure - azure devops 访问日志
- python - 使用 Python 密码保护 Excel 文件
- sql - 获取最后一条消息 postgres
- python - 'float' 对象在 python 中不可迭代
- python - 从 django 中的文件添加选项