I have an array which I want to pass in a dropdown and select what user is choosing on submit and return
An HTTP Call returns this structure
[
"3/cat",
"1/apple",
"2/boy",
"5/egg"
"4/dog",
]
How it is defined..
//defined in a different file
export class SchemaConfig {
....
....
items: string[];
}
//defined in main file
export class ListCall implements OnInit {
items: SchemaConfig[];
ngOnInit() {
....
this.getlist();
}
getlist() {
this.loading = true;
this.httpcall.getlist()
.subscribe(
results => {
this.items = [];
let items = new SchemaConfig();
items = results;
items.sort(function(a, b) {
return a.localeCompare(b);
});
this.items.push(items);
});
}
}
This is how I define in HTML
<select>
<option *ngFor="let t of items">
{{ t }}
</option>
</select>
When this displays it comes as a long list of a single dropdown
1/apple,2/boy,3/cat,4/dog,5/egg
When I choose a particular array it displays it single
<select>
<option *ngFor="let t of items">
{{ t[0] }}
</option>
</select>
1/apple
Questions
- How do I get the items to be listed in a dropdown for each element separately?
- Please let me know what all I can correct above to make it better.
- When the item is selected I need to capture that and pass the value via a postResult() method which is doing a http call (that call is like this.httpcall.getlist() but need to pass a value back to this.httpcall.postResult(result)
CodePudding user response:
Here is a stackblitz which illustrates the underlying issue with your code:
Your error is this line:
this.items.push(items);
You are pushing an array into an array:
this.items.push([
"1/apple",
"2/boy",
"3/cat",
"4/dog",
"5/egg",
]);
Which leaves you with the structure:
[[
"1/apple",
"2/boy",
"3/cat",
"4/dog",
"5/egg",
]]
And when this outer array is iterated over, it leaves you with a comma separated representation of the internal array.
You can, as you have discovered, access the internal array directly.
I would change your code like so:
getlist() {
this.loading = true;
this.httpcall.getlist()
.subscribe(
results => {
results.sort(function(a, b) {
return a.localeCompare(b);
});
this.items = results;
});
}
You also have a misunderstanding in how your data types work.
Your SchemaConfig class is defined as:
export class SchemaConfig {
items: string[];
}
But you are attempting to assign an array of schemaConfigs when in fact your should have a single one with an array of items inside.
And then don't forget to add a value to your option:
<option *ngFor="let t of mySchemaConfig.items" [value]="t">
You'll then be able to use ngModel or reactive forms to post via the https service of your choice.