当调用setValue时,FormControl的ValueChanges事件不触发。

11

我有一个 Angular 4 的自动完成组件的代码:

在 FormGroup 中有一个 FormControl,它与 html 相关联,并且它能够完美地工作。

this.ProfileForm.controls["code"]

当我在文本框中更改时,valueChanges事件会触发。但是,当我通过编程方式更新formcontrol值时,valueChanges事件不会触发。

以下是我编写的代码行。

this.ProfileForm.controls["code"].setValue("someValue");

this.ProfileForm.controls["code"].valueChanges.subscribe(() => {
            console.log("modified");}, () => { console.log("error") }, () => { console.log("completed") });
任何建议都受到赞赏。

1
你确定你没有重新初始化表单吗? - Vova Bilyachat
你能否请发布完整的源代码?而不是来自不同地方的部分。 - Vova Bilyachat
在代码中你先调用了 setValue 再订阅吗? - Vova Bilyachat
是的,在代码中它定位正确。 - Bhimisetty
我无法创建一个plunker,因为它是巨大的代码。我只能提供上面的小代码。另一个要点是,valueChanges和setValue这两个语句在不同的方法中。ngOnInit()包含valueChanges()方法,而某些按钮点击则有setValue()方法。 - Bhimisetty
显示剩余2条评论
2个回答

11

先将其更改为订阅,然后再使用setValue

this.ProfileForm.controls["code"].valueChanges.subscribe(() => {
            console.log("modified");}, () => { console.log("error") }, () => { console.log("completed") });

this.ProfileForm.controls["code"].setValue("someValue");

因为在你的代码中,你正在更改值,而此时你还没有订阅。


正如注释中所述,代码的位置是您提到的正确位置。 - Bhimisetty
@Bhimisetty 你是什么意思? - Vova Bilyachat
我的代码就像这样。ProfileForm.controls["code"].valueChanges.subscribe(() => { console.log("已修改");}, () => { console.log("错误") }, () => { console.log("已完成") });this.ProfileForm.controls["code"].setValue("某个值"); - Bhimisetty
1
#"¤%/%#"§"! 我!这是一个热可观察对象吗?好的,感谢您的帮助 - 当它应该工作时我一直很沮丧 :D - MartinJH

0

或许这会有所帮助。 我曾由于错误的值设置而遇到过类似的问题。

this.formGroup = this._formBuilder.group({
  city: [new Location()]
});

this.cityControl = this.formGroup.get('city');

this.citiesListOptions = this.cityControl.valueChanges.pipe(
  map(name => this._filterCity(name))
);

当我使用这个时:

this.cityControl.patchValue(null); 

然后cityControl.valueChanges没有再次触发。

当我更正后,它就起作用了:

this.cityControl.patchValue(new Location() ) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接