Angular5 reactive Forms Listening for Changes 監聽表單變化

在html 中定義了 FromGroup,怎麼來監聽用戶輸入值的變化呢?html

能夠使用valueChanges 來訂閱變化。ui

this.myForm.valueChanges.subscribe(val => {
    // to do
});

首先,實例化FromGroupthis

initFormControls() {
    this.form = this._formBuilder.group({
      ipCtrl: new FormControl('', [Validators.required, Validators.pattern(Validator.ipReg)]),
      snmpCommunityCtrl: new FormControl('', [Validators.maxLength(24)]),
      descriptionCtrl: new FormControl('', [Validators.maxLength(255)]),
      enabledBGPCtrl: new FormControl(),
    });
  }

而後,定義一個 onFormChanges 方法來監聽 form的變化code

onFormChanges(): void {
    // watch the whole form
    this.form.valueChanges.subscribe(val => {
      console.log('onFormChanges', val);
    });

    // watch the specific form control
    this.form.get('enabledBGPCtrl').valueChanges.subscribe(val => {
      console.log('onFormChanges', val);
    });
    
  }

在ngInit 時調用以上兩個方法orm

ngOnInit() {    

    this.initFormControls();
    
    this.onFormChanges();
  }
相關文章
相關標籤/搜索