我正在尝试使用角度材料自动完成来创建自定义组件,这样我就可以在代码中的任何地方使用它,因为我正在传递动态数组,对于每个数组,我都有不同的键。
我试过的是
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);
所以它会把还给我
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>
意味着我想通过字段,这样它就可以自动遍历并向我显示数据
我会这样做,但函数应该是一个管道,或者数据需要在开始时计算(当使用setter触发数据输入时(
fields: Array<string> = [];
// build an array with your path
@Input() set field(fields: string) {
this.fields = fields.split('.');
}
// function to retreive the data
// You need to make this a pipe
getValue(option: any): string {
let temp: any;
if (this.fields.length > 0 && option) {
this.fields.forEach(field => {
temp = option[field];
})
}
return temp;
}
html
<mat-option *ngFor="let option of items " [value]="option">
{{ getValue(option) }}
</mat-option>
简单的解决方案,但请进一步阅读以了解哪里出错
更改
this.fields = field.split(".");
{{option[field]}} ---> {{option[fields[0]][fields[1]]}}
让我简化一下,
您基本上是在尝试访问作为数组一部分的对象的内部属性,因此,试图传递现场数据并直接获取,
就项目而言,它应该是
items[index][ObjectAttr][innerObjAttr]
对于您的样品JSON1,它应该是
`items[index][caption][default]`
但你现在做的是
items[index][[caption][default]]
这将不起作用
我找到了ans,感谢@ukn和@shrivenkata pavan kumar mhs
getValue(Obj): any {
var objPath=this.field.split(".");
var s="Obj";
for(var i=0;i<this.field.split(".").length;i++){
s=s+"['"+objPath[i]+"']";
}
return eval(s);
}