简体   繁体   English

Angular 4将选择选项绑定到控制器

[英]Angular 4 bind select option to controller

I get a list of categories from my service, and i want to bind the category of my controller with the option selected in my select, what i tried: 我从服务中获得了类别列表,并且我想将控制器的类别与在我的选择中选择的选项绑定在一起,这是我尝试过的:

<select class="form-control" id="category" [(ngModel)]="category">
        <option *ngFor="let category of categoryservice.getCategories()">
          {{category.name}}
        </option>
</select>

My controller: 我的控制器:

category : Category = new Category(0, '', '', 0);

constructor(private categoryservice : CategoryService) { }

ngOnInit() {
}

With this code i get the error: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions. 使用此代码,我得到一个错误: 如果在表单标记中使用ngModel,则必须在ngModelOptions中设置name属性或将表单控件定义为“独立”。

But i'm not using ngModel within a form, so i don't know what could be the problem. 但是我没有在表单中使用ngModel,所以我不知道可能是什么问题。

Thanks! 谢谢!

Just add a name attribute to your select 只需将名称属性添加到您的select

    <select class="form-control" name="categoryDrpDown" id="category" 
 [(ngModel)]="category">
        <option *ngFor="let category of categoryservice.getCategories()" [ngValue]="category">>
          {{category.name}}
        </option> 
     </select>

Also you need to call the method getCategories() inside ngOninit and use the categories array only in template. 另外,您需要在ngOninit中调用方法getCategories() ,并且仅在模板中使用Categories数组。

<select class="form-control" id="category" [(ngModel)]="category">
        <option *ngFor="let category of categories">
          {{category?.name}}
        </option>
</select>

and inside component 和内部组件

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM