[英]Angular 4 bind select option to controller
我从服务中获得了类别列表,并且我想将控制器的类别与在我的选择中选择的选项绑定在一起,这是我尝试过的:
<select class="form-control" id="category" [(ngModel)]="category">
<option *ngFor="let category of categoryservice.getCategories()">
{{category.name}}
</option>
</select>
我的控制器:
category : Category = new Category(0, '', '', 0);
constructor(private categoryservice : CategoryService) { }
ngOnInit() {
}
使用此代码,我得到一个错误: 如果在表单标记中使用ngModel,则必须在ngModelOptions中设置name属性或将表单控件定义为“独立”。
但是我没有在表单中使用ngModel,所以我不知道可能是什么问题。
谢谢!
只需将名称属性添加到您的select
<select class="form-control" name="categoryDrpDown" id="category"
[(ngModel)]="category">
<option *ngFor="let category of categoryservice.getCategories()" [ngValue]="category">>
{{category.name}}
</option>
</select>
另外,您需要在ngOninit中调用方法getCategories() ,并且仅在模板中使用Categories数组。
<select class="form-control" id="category" [(ngModel)]="category">
<option *ngFor="let category of categories">
{{category?.name}}
</option>
</select>
和内部组件
category : Category = new Category(0, '', '', 0);
categories : Category[] = []
constructor(private categoryservice : CategoryService) { }
ngOnInit() {
this.categoryservice.getCategories().subscribe((response) => {
this.categories = response;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.