2017-04-19 121 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代碼)認爲克里斯