从服务

时间:2016-04-25 08:41:27

标签: angular

我有一个类,它有一个名为filter service的服务,它被注入到类中。我正在使用此服务创建一个选择框并列出所有选项。我正在调用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));
            });
    }
}

2 个答案:

答案 0 :(得分:1)

这可能有效:

    <option *ngFor="let typ of filter.AccountTypes;let i = index; let first=first" [attr.selected]="first ? 'selected' : null" [value]="typ.Id">{{typ.Name}}</option> 

export class FilterCollection {
public AccountTypes;
 getAccountTypes() {
        this.orgId = this._localstore.get('orgId');
        this._http.get('Organisations/' + this.orgId + '/AccountTypes')
            .map(res => res.json())
            .map(res => {
                this.AccountTypes = [];
                for (var x of res.Data)
                    this.AccountTypes.push(new AccountTypesModel(x));
            });
    }
}
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().toPromise().then(val => this.accountType = this.filter.AccountTypes[0] ;
  }
}

答案 1 :(得分:0)

You could leverage the index of the element in the loop to set the value of the selected attribute. Don't foget to set null if it's not the first element to remove the selected attribute from the option tag.

<select class="form-control" [ngModel]="accountType"> 
  <option *ngFor="#typ of filter.AccountTypes;#i = index" 
     [selected]="i===1 ? 'selected': null"
     [value]="typ.Id">{{typ.Name}}</option> 
</select>

See this plunkr: https://plnkr.co/edit/9AzoSzWU0DTFa5chF2SR?p=preview