2017-04-05 45 views
0

我有一個窗體和幾個如下所示的函數。Angular 2使用patchValue從REST API設置數據

ngOnInit() { 
     this.buildForm(); 
     this.loadData(); 
     this.success = false; 
    } 

    loadData(): void { 
     this.countryService.getCountries().subscribe(list => { 
      this.countries = new Select2Mapper('countryCode', 'name').getData(list); 
      this.setDefaultCountry(); 
     }); 
    } 

    setDefaultCountry(): void { 
     console.log('Setting default country'); 
     console.log(this.accountCreateForm.get('company').value); 
     this.accountCreateForm.get('company').patchValue({ 
      countryCode: "US" 
     }); 
    } 

    buildForm(): void { 

     this.accountCreateForm = this.fb.group({ 
      company: this.fb.group({ 
       companyName: ['', [WPValidator.companyName]], 
       countryCode: ['', [Validators.required]] 
      }), 
      administrative: this.fb.group({ 
       firstName: ['', [WPValidator.nameMandatory]] 
      }) 
     }); 

     console.log('Form built'); 

     this.accountCreateForm.valueChanges 
      .subscribe(data => this.onValueChanged(data)); 

     this.onValueChanged(); // (re)set validation messages now 

    } 

在上面的例子中,我可以看到setDefaultCountry setDefaultTimeZone在buildForm之後被調用。我不明白爲什麼新的價值觀反映在用戶界面中。我在UI中看到的是完整的值列表。它沒有顯示補丁值。在設置默認值之前或之後,是否需要觸發任何事件?

此外,當我在設置默認值即打印補償值後打印表格值時,我可以看到更新後的值。

如果它的事項,我使用的是選擇2 jQuery插件的角度包裝器國家下拉

+0

我試過補丁之後調用ChangeDetectorRef。這並不奏效。 – TechCrunch

+0

NgZone也沒有運氣:( – TechCrunch

回答

0

您需要導入changeDetectionRef並調用detectChanges()。

import {ChangeDetectorRef} from '@angular/core'; 

那麼你的類中,

constructor(private _cdr : ChangeDetectorRef){ 

} 

再打_cdr.detectChanges()patchValue()

+0

正如我在問題的評論中提到的那樣,我之前嘗試過這樣做,但它不起作用 – TechCrunch

+0

@TechCrunch嘗試''applicationRef.tick()'' – CruelEngine

+0

這並沒有工作。 ,我正在使用一個Select2包裝 - 在這個 - https://github.com/NejcZdovc/ng2-select2/issues/76。 – TechCrunch