Pushing to FormArray removes disabled status on FormControl in FormGroup

时间:2017-08-13 14:06:57

标签: angular angular2-forms

Angular Forms

Okey, so I have this weird angular Form Problem. I have an app that dynamically creates forms from a specific structure. What I am trying to achieve is something like this.

new FormArray([
new FormGroup(
    id: new FormControl({value: "", disabled: true}), 
    id2: new FormControl()),
]);

This almost works the problem that I am having is that specific FormControls needs to be disabled. As long as the group exists the field is disabled but when i add it to the form array the disabled state disappears somehow.

This is my code for creating the array

createTableRows(tableField){

let array = [];

for(let k = 1; k <= tableField.Count; k++){
    let row = tableField.GetRowValues(k);
    let fieldRow = {};
    for(let j = 0; j < row.row.length; j++){
        let cell = row.row[j];

        if(cell.required){
          fieldRow[cell.id] = new FormControl(cell.value, Validators.required);
         } else {
           fieldRow[cell.id] = new FormControl(cell.value);
         }

         if(cell.enabled){
            fieldRow[cell.id].enable();
          } else {
            fieldRow[cell.id].disable();
          }

      }
      array.push(new FormGroup(fieldRow));
  }
  return new FormArray(array);
}

Edit: Made a rookie mistake. Somehow i managed to enable the formarray and then the children is enabled to. Have to work around this somehow.

1 个答案:

答案 0 :(得分:0)

angular.io/api/forms/FormArray#adding-or-removing-controls

  

不要修改用于实例化的AbstractControls数组   FormArray直接,因为这将导致奇怪和意外   行为,如破坏变化检测。

我解释这个措辞的方式。你可能需要创建FormArray,然后在构建它之后在数组内修改它。