Angular reactive form hidden input not binding?

前端 未结 2 965
闹比i
闹比i 2021-02-09 01:31

I have a reactive form where I create the controls from my data model. Initially, everything is sorted by a datapoint called the \"processingOrder\" in numerical order.

2条回答
  •  悲哀的现实
    2021-02-09 02:24

    Add this to the bottom of the move up/down handling method,

    move(shift, currentIndex) {
      const rules = this.rulesForm.get(['ruleData', 'rules']);
    
      let newIndex: number = currentIndex + shift;
      if(newIndex === -1) {
        newIndex = rules.length - 1;
      } else if(newIndex == rules.length) {
        newIndex = 0;
      }
    
      const currentGroup = rules.at(currentIndex);
      rules.removeAt(currentIndex);;
      rules.insert(newIndex, currentGroup)
    
      // logic to re-calculate processingOrder in the correct ascending order
      let i = 0;
      this.rulesForm.get(['ruleData', 'rules']).controls.forEach((elem) => {
        i++;
        elem.get('processingOrder').setValue(i);
      });
    }
    

    It basically re-assigns the processingOrder numbers in ascending order based on the formArray length. Hope it helps. (Confirmed it working in plunker)

    You don't need the hidden input in the template for this to work. Also, if you specify more than one input controls (here input elements of type 'text' and 'hidden' for 'processingOrder') with the same formControlName then it probably is not gonna work as you expect in a reactive form.

提交回复
热议问题