【问题标题】:How to get input field name that value has changed [ Angular 6 ]如何获取值已更改的输入字段名称[Angular 6]
【发布时间】:2020-06-12 09:46:09
【问题描述】:

我尝试了响应式表单 valueChanges 但 valueChanges 方法不返回已更改的输入字段名称。

我认为代码是这样的。但我认为这不是聪明的方式。因为我必须比较每个输入字段。所以我需要更聪明的方法。

  // get init view data from local storage
  this.localstorageService.getPlaceDetail().subscribe(data => {
    this.initPlaceDetail = data;
    // watch changed value 
    this.editPlaceForm.valueChanges.subscribe(chengedVal => {

      if (chengedVal['ja_name'] !== this.initPlaceDetail.languages.ja.name.text) {
        this.changedJA = true;
      }
      if (chengedVal['ja_romaji'] !== this.initPlaceDetail.languages.ja.name.romaji) {
        this.changedJA = true;
      }
      // ...... I have to check all input fields??
    });
  });

【问题讨论】:

    标签: angular-reactive-forms angular6


    【解决方案1】:

    我正在从数组中添加表单控件,这样的东西对我有用。只需引用您需要的项目,而不是期望可观察到的 valueChanges 将其传递给您。

    myFields.forEach(item => {
        const field = new FormControl("");
        field.setValue(item.value);
        field.valueChanges.subscribe(v => {
              console.log(item.name + " is now " + v);
        });
    });
    

    【讨论】:

      【解决方案2】:

      这是我在表单中获得更改控制的方式。

      我为关心的人分享。

      获取列表控件更改值的方法

      private getChangedProperties(form): any[] {
      
          let changedProperties = [];
      
          Object.keys(form.controls).forEach((name) => {
            let currentControl = form.controls[name];
      
            if (currentControl.dirty)
              changedProperties.push({ name: name, value: currentControl.value });
          });
      
          return changedProperties;
        }
      

      如果您只想获得最新更改的控件,您可以使用

      var changedProps = this.getChangedProperties(this.ngForm.form);
      
      var latestChanged = changedProps.reduce((acc, item) => {
      if (this.changedProps.find(c => c.name == item.name && c.value == item.value) == undefined) {
             acc.push(item);
        }
        return acc;
      }, []);
      

      【讨论】:

        【解决方案3】:

        您可以监听每个表单控件的值更改事件,而不是监听整个表单更改,如下代码所示:

        this.myForm.get('ja_name').valueChanges.subscribe(val => {
            this.formattedMessage = `My name is ${val}.`;
          });
        

        【讨论】:

        • 谢谢。但是这种方式也必须检查所有字段对吗?
        • 如果我在一个表单中有 50 个字段,并且当表单 valueChanges 我想知道发生了什么变化 - 即。 50 valueChanges 订阅者不理想?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 2014-04-09
        • 2019-07-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多