javascript - Angular 形式禁用对 valueChanges 的控制

标签 javascript angular

当我的表单组值之一发生更改时,我尝试禁用表单控件,但问题是方法 disable()enable() 也会更新表单状态,所以我有一个无限循环。

@Component({
  selector: 'my-app',
  template: `
   <form [formGroup]="questionForm">

     <input type="text" formControlName="question" />

     <input type="text" formControlName="other"/>
   </form>
  `,
})
export class App {

  constructor(private fb: FormBuilder) {  
     this.questionForm = this.fb.group({
       question: [''],
       other: ['']
     });
  }

  ngOnInit() {
     this.questionForm.valueChanges.subscribe(v => {
       if(v.question === 'test') {
         this.questionForm.get('other').disable();
       } else {
          ...enable()
       }
     })
  }

}

如何解决这个问题?

最佳答案

嗯,根据official docs您可以使用指令进行自定义验证,这当然可以在您的情况下应用检查用户输入内容的逻辑,然后禁用和启用其他字段。那里有相当多的代码,sooooo...

...如果您不需要所有那堆代码,您也可以进行较小的修改。让我们调用一个函数来检查用户输入的内容。我们还需要绑定(bind)this,所以我们可以引用questionForm:

 this.questionForm = this.fb.group({
   question: ['', [this.checkString.bind(this)]],
   other: ['']
 });

然后是函数:

checkString(control: FormControl) {
  if(control.value == 'test') {
    this.questionForm.get('other').disable()
  }
  // we need to check that questionForm is not undefined (it will be on first check when component is initialized)
  else if (this.questionForm) { 
    this.questionForm.get('other').enable()
  }
}

这似乎达到了目的。

Demo

希望这有帮助! :)

关于javascript - Angular 形式禁用对 valueChanges 的控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43479622/

相关文章:

Angular - 如果已将不必要的 ngModules 导入别处,导入它们是否会增加文件大小?

angular - 不能扩展 Angular Material 表

jquery 数据表 : fetch next 25 rows from databse on next page button of jQuery datatable

javascript - 预加载背景图片

javascript - node-red循环遍历全局变量

javascript - 通过ajax(chrome)在vanilla js中以编程方式触发文件输入点击

angular - chromedriver 版本错误。 Protractor 要求 2.31

Angular2 upgradeComponent 如何进行双向绑定(bind)

javascript - (WordPress/Ajax) 引用错误 : Can't find variable: ajaxobject

javascript - 根据 PHP Foreach 循环中的 select 显示更多输入