I am currently working on implementing angular material autocomplete in a custom component that can be easily used throughout my code. The challenge I am facing is setting up dynamic arrays with different keys for each array.
Here is what I have attempted so far:
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);
This will return ['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>
I also tried using "." like: "caption.default"
Unfortunately, it did not work as expected. Can anyone help me find a solution?
My goal is to create a generic component that can be easily utilized by filling in the necessary data through @Inputs. For example, if I have two JSON objects:
JSON-1
[{
"caption": {
"default": "Asset ID"
}
},
{
"caption": {
"default": "Asset ID"
}
}]
and My second JSON object is JSON-2
[{
"name": {
"anything": "Asset ID"
}
},
{
"name": {
"anything": "Asset ID"
}
}]
For the first JSON (json-1), I would use the following:
<app-autocomplete [items]="data.attributes" [field]="'caption.default'" inputType="text" inputPlaceholder="placeholder"></app-autocomplete>
And for the second JSON (json-2), I would use:
<app-autocomplete [items]="data.attributes" [field]="'name.anything'" inputType="text" inputPlaceholder="placeholder"></app-autocomplete>
My aim is to pass fields dynamically so that the component can traverse automatically and display the relevant data.