[英]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.