繁体   English   中英

Angular:关闭并重新打开模态后将表单重置为原始值

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

我有这个问题 - 我有一个项目部分 - 在项目点击上,有一个模式 window 打开,可以编辑文本区域内项目的文本。 但是,当我编辑文本并取消/关闭模态然后再次重新打开时,文本位于先前修改的 state 中。我的目标是将文本重置为正确的现有 state - 因此在关闭之前对文本进行任何更新模式被删除。

你能建议一些解决方案/function/链接吗?

<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 ...
  }
}

我认为这里的问题是,当您在模式打开时编辑表单时,您正在更改表单text字段中的值。 因此,如果模态窗口关闭并再次打开, text字段中的相同当前值也会出现在模态窗口中。

可以将整个表单放在模态本身内,以便每次打开模态时 state 都是干净的,或者实现类似于Angular Material 的MatDialog的东西

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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