2017-04-19 119 views
0

我试图创建一个编辑表单客户对象, 第一,我从服务获取数据,然后初始化形式Angular2材料 - 不能选择的选项设置为MD-选择

ngOnInit(){ 

    this.clientService.getCountries().subscribe(
     (result:any) => { 
      this.countries = result.countries; 
     } 
    ); 

    this.subscription_route = this.route.params.subscribe(
     (params: any) =>{ 
      if(params.hasOwnProperty('id')){ 
       this.client_guid = params['id']; 
       this.subscription_service = this.clientService.getClient(this.client_guid).subscribe(
        (result:any) => { 
        this.client = result.client; 
         this.initForm(); 
       } 
      ); 
      } 
     } 
    ); 

    } 

我在initForm看起来是这样的:

private initForm(){ 
     this.selectedOption = this.client.country_id; 
    this.clientForm = this.formBuilder.group({ 
      name:[this.client.name,Validators.required], 
      email:[this.client.email], 
      vat_number:[this.client.vat_number], 
      payment_terms_id:[this.client.payment_terms_id], 
      address:[this.client.address], 
      city:[this.client.city], 
      postal:[this.client.postal], 
      country_id:[this.client.country_id], 
      accounting_key:[this.client.accounting_key], 
      payment_amount:[this.client.payment_amount] 
     }); 
    } 

,然后在我的HTML模板,我有这样的MD-选择

<md-select placeholder="country" formControlName="country_id"> 
    <md-option *ngFor="let country of countries" [value]="country.id">{{ country.name }}</md-option> 
</md-select> 

enter image description here

我不能够设置,我从服务器

回答

1

我到处搜索,并没有发现任何回答让所选择的选项,所以我试图用属性和属性的发挥。 我注意到,当我不使用* ngFor选择的选项被选中,所以我觉得这个问题是与[value]属性 这种方式为我工作:

<md-select placeholder="country" [(ngModel)]="selectedOption" formControlName="country_id"> 
    <md-option *ngFor="let country of countries" value="{{country.id}}">{{ country.name }}</md-option> 
</md-select> 
+0

在你的答案绑定所选择的选项与'[(ngModel)]'的值。我想你可以查看这篇博客文章,了解有关Angular绑定的更多信息:https://angular-2-training-book.rangle.io/handout/components/app_structure/two_way_data_binding.html – fuma

0

如果您正在使用复杂的形式,你可以这样做

<md-select placeholder="country" [formControl]="clientForm.controls['country_id']"> 
    <md-option *ngFor="let country of countries" [value]="country.id">{{ country.name }}</md-option> 
</md-select> 

这将工作,如果你喜欢更新

clientForm.controls['country_id'].setValue(2); 

例如形式值。

希望这会有所帮助。

类(在你的问题unlinke代码)认为克里斯