简体   繁体   中英

Angular: reset the form back to it´s original value after closing and reopening the modal

I have this problem - I have an items section - on the item click, there is a modal window opened with the possibility to edit text of the item inside textarea. However, when I edit the text and cancel/close the modal and then reopen again, the text is in the previously modified state. My goal is to reset the text to the correct existing state - so any update of the text before closing of the modal is removed.

Can you suggest some solution / function / link?

<form [formGroup]="editForm" (ngSubmit)="editItem()">
  <textarea rows="3" formControlName="text"></textarea>
  <button type="submit">Save</button>
  <button type="button" (click)="closeModal()">Close</button>
</form>
export class EditItemComponent implements OnInit, OnChanges {
  @Input() item: Item;
  editForm: FormGroup;

  ngOnInit(): void {
    this.editForm = new FormGroup({
      text: new FormControl('', [Validators.required, Validators.minLength(3)]),
    });
  }

  ngOnChanges(): void {
    this.editForm.controls.text.setValue(this.item.text);
  }

  editItem():void {
  //edit item logic
  }

  closeModal(): void {
    //logic for closing modal
    //here I know I can simply set the editForm text 
    //back to the original text but I want the general 
    //solution which will handle other possible scenarios - clicking away 
    //from modal closes the modal, pressing esc closes the modal ...
  }
}

I think the issue here is that when you edit the form when the modal is open, you're changing the value in the text field of the form. So if the modal is closed and opened again, the same current value in the text field is also present in the modal.

You could either place your entire form inside the modal itself so that the state is clean each time the modal is opened, or implement something similar to Angular Material's MatDialog .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM