我试图使用角材料自动完成来创建自定义组件,这样我可以在代码中的任何地方使用它,因为我传递的是动态数组,对于每个数组,有不同的键被卡在一个点上。
我试过的是
app.component.html
<app-autocomplete [items]="data.attributes" [field]="'caption.default'" inputType="text" inputPlaceholder="placeholder"></app-autocomplete>autocomplete.component.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还给我
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“
没有用请任何人帮我解决这个问题.!!
我正在尝试使用我的组件泛型,所以在任何我可以使用的地方,只需填充一些数据@输入,比如如果我有两个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>意味着我想要传递字段,这样它就可以自动遍历并显示数据。
发布于 2019-11-15 19:11:31
我会这样做,但函数应该是管道,或者数据需要在开始时计算(当数据的输入是使用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> 发布于 2019-11-15 19:29:00
简单的解决方案,但要进一步阅读才能知道哪里出了问题
变化
this.fields = field.split(".");
{{option[field]}} ---> {{option[fields[0]][fields[1]]}}让我简化一下,
您基本上是试图访问作为数组一部分的对象的内部属性,因此试图传递字段数据并直接获取它,
关于项目,它应该是
items[index][ObjectAttr][innerObjAttr]对于您的示例JSON1,应该是
`items[index][caption][default]`但你所做的却是
items[index][[caption][default]]这是行不通的
发布于 2019-11-15 20:04:43
我找到了“谢谢”,“ukn”和“shrivenkata 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);
}https://stackoverflow.com/questions/58882671
复制相似问题