我正在尝试用数据库中的项目填充引导列表,下面是我所做的:
这是我的HTML:
还有[(ngModel)]=“mainGroups”
<div class="form-group">
<label class="control-label dash-control-label col-xs-3">Group category:</label>
<div class="col-xs-9">
<select class="form-control dash-form-control select2" style="width: 100%;"
data-minimum-results-for-search="Infinity" name="articleGroups" [(ngModel)]="mainGroups">
</select>
</div>
</div>
这是我的
ts
文件内容:
@Component({
selector: 'product-new',
templateUrl: './product-new.component.html',
styleUrls: ['./product-new.component.css']
})
export class ArticleNewComponent implements OnInit {
id: string;
article: Article;
// Here I'm creating array that will hold all my categories / groups
mainGroups: Observable<Group[]>;
constructor(private _groupService: GroupService) {
this.article = new Article();
this.article.isActive = true;
// Here I'm getting all groups and definately they are not empty
this.mainGroups = this._groupService.getAll();
}
}
这是我的
categories.service.ts
文件,它为我提供了getAll方法:
getAll(): Observable<Group[]> {
return this._http.get<Group[]>(url)
.catch(
(error: HttpErrorResponse) => {
return Observable.throw(error);
});
}
毕竟我的选择列表是空的,如下所示:
任何形式的帮助和建议都会很棒!
请注意,因为这是我的第一个angular应用程序,所以在我将其与ngModel绑定之前,可以在构造函数中实例化模型对象,还是应该在其他地方进行实例化?
或者,我不应该直接在ngModel中使用模型属性,这意味着我应该创建一个本地变量,该变量应该被绑定,在保存时,我将创建新对象并用这些变量值填充它的属性?
谢谢
在David的帮助下编辑,可能的解决方案2:
<div class="form-group">
<label class="control-label dash-control-label col-xs-3">Grupa:</label>
<div class="col-xs-9">
<select class="form-control dash-form-control select2" style="width: 100%;"
data-minimum-results-for-search="Infinity" name="articleGroups" [(ngModel)]="selectedGroup">
<option [ngValue]="group" *ngFor="let group of mainGroups">{{group.title}}</option>
</select>
</div>
</div>
mainGroups: Group[];
constructor(private _globalHelperService: GlobalHelperService, private _groupService: GroupService) {
this._groupService.getAll().subscribe(groups => this.mainGroups = groups);
}