gpt4 book ai didi

javascript - 有没有办法以 Angular 形式将 json 键作为字符串 @Input() 传递

转载 作者:行者123 更新时间:2023-11-28 03:23:38 26 4
gpt4 key购买 nike

我正在尝试使用 Angular Material 自动完成来创建自定义组件,这样我就可以在代码中的任何位置使用它,因为我正在传递动态数组,并且对于每个数组,我都卡在了一个点上。

我尝试的是

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']['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>

意味着我想传递字段,以便它可以自动遍历并显示数据

最佳答案

我会做类似的事情,但函数应该是一个管道,或者需要在开始时计算数据(当使用 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>

关于javascript - 有没有办法以 Angular 形式将 json 键作为字符串 @Input() 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58882671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com