我有一个类,并有一个名为过滤器服务的服务注入到类中。我正在使用此服务创建一个选择框并列出所有选项。我调用ngOnInit方法调用 filter.getAccountTypes()方法,以便该服务具有填充下拉列表的数据。从服务的选择框中选择一个默认值
export class ActionsAddComponent {
constructor(public filter: FilterCollection, public _form: FormBuilder) {
this.actionForm = this._form.group({
AccountId: ['', Validators.required],
Type: ['', Validators.required]
});
}
ngOnInit() {
this.filter.getAccountTypes();
}
在视图中我有以下代码
<select class="form-control" [ngModel]="accountType">
<option *ngFor="#typ of filter.AccountTypes;#i = index" selected="selected" [value]="typ.Id">{{typ.Name}}</option>
</select>
因为filter.AccountTypes是我不能够设置ngModel的默认值作为第一行里面的服务加载。是否有任何简单的解决方法。这样我可以选择第一行并仍然有ngmodel。
export class FilterCollection {
public AccountTypes;
getAccountTypes() {
this.orgId = this._localstore.get('orgId');
this._http.get('Organisations/' + this.orgId + '/AccountTypes')
.map(res => res.json())
.subscribe(res => {
this.AccountTypes = [];
for (var x of res.Data)
this.AccountTypes.push(new AccountTypesModel(x));
});
}
}
雅那是后话,如果我能得到正在使用该服务的组件中的数据,将工作。现在数据出现在服务中,组件不能获取数据。所以我不能设置默认值。 – harikrish
我更新了我的答案。尽管如此,我还没有尝试过。 –
我明白了,我能够得到第一行的选择。该模型仅更新事件。是否可以将模型设置为默认值 – harikrish