2017-04-05 47 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