【问题标题】:Angular 2 set data from REST API using patchValueAngular 2 使用 patchValue 从 REST API 设置数据
【发布时间】:2017-04-06 10:27:19
【问题描述】:

我有一个表单和一些如下所示的函数。

  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 中。我在 UI 中看到的只是完整的值列表。它没有显示补丁值。我需要在设置默认值之前或之后触发任何事件吗?

另外,当我在设置默认值(即patchValue)后打印表单值时,我可以看到更新后的值。

如果重要的话,我会在 select2 jquery 插件上使用角度包装器,用于国家下拉菜单

【问题讨论】:

  • 我尝试在补丁后调用 ChangeDetectorRef。那也没用。
  • NgZone 也没有运气 :(

标签: angular angular2-forms


【解决方案1】:

你需要导入changeDetectionRef并调用detectChanges()。

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

然后在你的班级里,

constructor(private _cdr : ChangeDetectorRef){

}

稍后在patchValue() 之后调用_cdr.detectChanges()

【讨论】:

  • 正如我在问题的 cmets 中提到的,我之前尝试过,但没有成功
  • @TechCrunch 尝试applicationRef.tick()
  • 那也没用。如果有帮助,我将使用 Select2 包装器,如 github.com/NejcZdovc/ng2-select2/issues/76。
猜你喜欢
  • 2017-03-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多