Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
简单Angular2反应式表单控制启用状态更改_Angular_Rxjs_Reactive Programming_Observable - Fatal编程技术网

简单Angular2反应式表单控制启用状态更改

简单Angular2反应式表单控制启用状态更改,angular,rxjs,reactive-programming,observable,Angular,Rxjs,Reactive Programming,Observable,我有一个带有first\u name和last\u name字段的表单 当这两个字段都输入了值时,我希望启用相同表单中的另一个formControl 我知道我可以订阅这样的更改: createForm() { this.myForm = new FormGroup({ first_name: this.first_name, last_name: this.last_name, email: this.email, mobile: th

我有一个带有
first\u name
last\u name
字段的表单

当这两个字段都输入了值时,我希望启用相同表单中的另一个formControl

我知道我可以订阅这样的更改:

  createForm() {
    this.myForm = new FormGroup({
      first_name: this.first_name,
      last_name: this.last_name,
      email: this.email,
      mobile: this.mobile,
      salutation: this.salutation
    });
    this.myForm.valueChanges.subscribe(data => console.log('form changes', (!data.first_name == !data.last_name)));
  }
当两个值都设置好时,它会登录到控制台并显示“true”

您可以从angular github上看到,我们不能/不应该将其设置为属性并绑定
[disabled]=
(核心团队似乎仍在处理此问题)

那么,如何使用上面valueChanges流的结果将另一个控件实际设置为启用状态呢

在OnInit中,根据以下指南将其禁用:

this.salutation = new FormControl({value:'', disabled: true}, Validators.required); 
更新

抱歉,我忘了提及我已经在OnInit中尝试过这个:

this.myForm.valueChanges.subscribe(data => {
  if (!data.first_name == !data.last_name) {
    this.salutation.enable();
  };
}) 

这不起作用,它抛出控制台错误:
超出了最大调用堆栈大小

在订阅函数中,执行以下操作

this.myForm.controls["controlToEnable"].enable();

超出的堆栈大小是解决此问题的线索。由于流是“连续”的,我的代码一直将控件设置为enabled,但当然,它只需要启用一次

因此,添加一个检查解决了问题,现在它可以工作了:

this.myForm.valueChanges.subscribe(data => {
  if (!data.first_name == !data.last_name && this.myForm.controls['salutation'].disabled) {
    this.myForm.controls['salutation'].enable();
  };
}) 

更多信息

谢谢,我试过了。它不工作,并且还会抛出超出最大堆栈大小的错误。我要补充一个问题来说明,也许我的代码错了。