Display and update FormGroup inside FormArray

后端 未结 1 697
遇见更好的自我
遇见更好的自我 2021-01-28 05:24

I am displaying a FormArray with an *ngFor. What i am trying to do is when i click on an item in the ngFor, to populate the with that items \'task\' property.

Additiona

相关标签:
1条回答
  • 2021-01-28 05:50

    you can declare a variable

    control:FormControl
    

    And use in your input formControl

    <input [formControl]="control" />
    

    Simply on click

    (click)="control=item.get('task')
    

    But I think you want to "edit in place". For this you need two variables and as usually I go to make a getter to the formArray

    itemSelected:number=-1;
    dropping:boolean=false
    get items()
    {
        return (this.myForm.get('items') as FormArray)
    }
    

    Our .html is like

    <form [formGroup]="myForm">
        <div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
    
            <div [id]="i" class="example-box" 
          [cdkDragDisabled]="itemSelected==i"
          (cdkDragDropped)="dropping=false"
                (cdkDragMoved)="dropping=true;itemSelected=-1"
                *ngFor="let item of items.controls; let i=index;" cdkDrag>
                <span *ngIf="itemSelected!=i" style="cursor:text" 
              (click)="!dropping && focus(i)" >
            {{item.value.task}} to be
        </span>
                <input #input *ngIf="itemSelected==i" [formControl]="item.get('task')" 
               (blur)="itemSelected=-1">
        </div>
    </div>
    </form>
    

    NOTE: to use the property cdkDragDisable you need updated your references, in "@angular/cdk": "7.0.3" you has not this property, so you need update to Angular 9 too

    See how, if "i=selectedIndex" it's showed the "input" and the cdkDrag is disabled. We need mannage when we click and when we want to drag. for this, I use the variable dropping that is true when you move and false when dropped, moreover, we make nothing if is dropping is true, the (click)="!dropping && focus(i)"

    Well, the function focus put the variable itemSelected to the value of the row and make the focus. The focus need make in a setTimeout to give a change to Angular to show the input

      focus(i:number)
      {
        this.itemSelected=i
        setTimeout(()=>{
          this.input.nativeElement.focus()
        })
      }
    

    Finally, the drop function, need take account that the function moveItemInArray is thinking to work with arrays, not with formArrays, so

      drop(event: any) {
        const array=this.items.value //get the value of the formArray
        moveItemInArray(array, event.previousIndex, event.currentIndex); //move the value
        array.forEach((x:any,i:number)=>x.position=i)  //recalculate the position
        this.items.setValue(array)  //make a setValue
      }
    

    You can see in this stackblitz

    0 讨论(0)
提交回复
热议问题