我有一个数组,我想在下拉列表中传递它并选择用户在提交和返回时选择的内容
HTTP 调用返回此结构
[
"3/cat",
"1/apple",
"2/boy",
"5/egg"
"4/dog",
]
怎么定义的。。
//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);
});
}
}
这就是我在 HTML 中定义的方式
<select>
<option *ngFor="let t of items">
{{ t }}
</option>
</select>
当它显示时,它是一个单一下拉列表的长列表
1/苹果,2/男孩,3/猫,4/狗,5/蛋
当我选择一个特定的数组时,它会单独显示
<select>
<option *ngFor="let t of items">
{{ t[0] }}
</option>
</select>
1/苹果
问题
你的错误是这一行:
this.items.push(items);
您正在将一个数组推入一个数组:
this.items.push([
"1/apple",
"2/boy",
"3/cat",
"4/dog",
"5/egg",
]);
这给你留下了结构:
[[
"1/apple",
"2/boy",
"3/cat",
"4/dog",
"5/egg",
]]
当这个外部数组被迭代时,它会给你留下一个逗号分隔的内部数组表示。
正如您所发现的,您可以直接访问内部数组。
我会像这样更改您的代码:
getlist() {
this.loading = true;
this.httpcall.getlist()
.subscribe(
results => {
results.sort(function(a, b) {
return a.localeCompare(b);
});
this.items = results;
});
}
您对数据类型的工作方式也存在误解。
您的 SchemaConfig 类定义为:
export class SchemaConfig {
items: string[];
}
但是您正在尝试分配一个 schemaConfigs 数组,而实际上您应该有一个包含一组项目的单个数组。
然后不要忘记为您的选项添加一个值:
<option *ngFor="let t of mySchemaConfig.items" [value]="t">
然后,您将能够使用 ngModel 或响应式表单通过您选择的 https 服务进行发布。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句