How to reset form control in angular 2

We have a list of drop-down menus, and when ever the drop-down menu is changed, I will show a button next to it. For this, I use the dirty formcontrol function. The button is initially hidden, and when the popup menu becomes dirty, I will close the button.

But after clicking the button, all other buttons should be hidden again along with other drop-down lists reset to their initial value. How to accomplish this task, because, according to my understanding, there is no way to make a dirty field irreplaceable.

<div class="form-group">
                                <h4 >Person {{i+1}}</h4>
                                <div >
                                    <div ><label class="control-label">Position</label></div>
                                    <div>
                                        <select [ngModel]="staff.position" (ngModelChange)="newPosition=$event;btn.hidden=0" #select="ngModel" name="position" placeholder="position">
                                            <option *ngFor="let i of instituteObj.academic_staff;let i=index" [value]="i+1">{{i+1}}</option>
                                        </select>
                                    </div>
                                    <div #btn [hidden]="!select.dirty" class="academic-move"><button (click)="changeStaffPosition(staff.position,newPosition);btn.hidden=1" type="button" class="btn btn-primary ">Move</button></div>
                                </div>
                            </div><br>

and my component function:

changeStaffPosition(currentPosition,newPosition){
    if(currentPosition < newPosition){
      for(let staff of this.instituteObj.academic_staff){
        if(staff.position > currentPosition && staff.position <= newPosition){
          --staff.position;
        }
      }
      this.instituteObj.academic_staff[currentPosition-1]['position'] = newPosition;  
    }
    else{
      for(let staff of this.instituteObj.academic_staff){
        if(staff.position >= newPosition && staff.position < currentPosition){
          ++staff.position;
        }
      }
      this.instituteObj.academic_staff[currentPosition-1]['position'] = newPosition;
    }

    this.instituteObj.academic_staff.sort((a,b) => {
      if(a['position']<b['position']){return -1}
      if(a['position']>b['position']){return 1}
      return 0;
    });
}

, , , , , , , .

+4
1

AbstractControl.markAsPristing()

select.markAsPristine();

, ,

@ViewChild('select') select;

...

this.select.markAsPristine();

, RC.4. . , RC.5 https://github.com/angular/angular/blob/3f08efa35dd334c61127fc8059b4d73b2bd0b866/modules/%40angular/forms/src/model.ts#L144

, , *ngIf="showForm", showForm true . false, , true ( ChangeDetectorRef detectChanges() )

+4

Source: https://habr.com/ru/post/1648622/


All Articles