【问题标题】:How to close a Bootstrap modal that contains a form when the form is submitted?提交表单时如何关闭包含表单的引导模式?
【发布时间】:2019-12-13 07:18:37
【问题描述】:

我有一个进入引导模式的表单,我想在用户单击提交按钮时关闭模式。看起来像这样:

export class AddPartModalComponent implements OnInit {

  @Input() id:number;
  closeResult: string;
  constructor(private modalService: NgbModal, private graphService:GraphService) { }

  ngOnInit() {
  }
  open(content) {
    this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return  `with: ${reason}`;
      }
    }

  onSubmit(form: NgForm) {
    //some code
  }

}
<ng-template #content let-modal>
  <div class="modal-header">
    <h4 class="modal-title" id="modal-basic-title">New element</h4>
    <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <form (ngSubmit)="onSubmit(f);" #f="ngForm"><!--here if I add 'modal.dismiss('Cross click')', it dosen't submit or it dosen't close the modal (depend if I add it before or after the 'onSubmit()')-->
      <!--some form content-->
      <button class="btn btn-primary" type="submit" [disabled]="f.invalid">Create</button>
    </form>
  </div>
</ng-template>

<button (click)="open(content)" style="background-color: transparent; height: 100%; width:100%; border: none;"><h4 style="height: 100%; width: 100%;">+ add part +</h4></button>

所以我不知道如何关闭模态,有没有办法在onSubmit函数中关闭它?

我尝试在onSubmit 函数中使用modal.dimiss,但它不起作用,我可能不明白引导模式是如何工作的,如果您有任何建议,我会很乐意阅读。

【问题讨论】:

    标签: html angular typescript bootstrap-4


    【解决方案1】:

    使用dismiss函数或dismissAll函数关闭modal。

    onsubmit() {
      ...
      this.modalService.dismissAll();
      //or
      this.modalService.dismiss();
    }
    

    【讨论】:

    【解决方案2】:

    看看这是否可行...将#content 而不是ngForm 传递到onSubmit。对您的 fn 中的内容调用驳回。

    <form (ngSubmit)="onSubmit(content);" #f="ngForm">
    

    在您的 HTML 模板中,您已通过模板引用将模态“内容”命名为“内容”。它将传递给您的函数...

    onSubmit(modal: NgbModal) { 
      modal.dismiss(); // <-- modal will be referring to the above template reference. It's type is NgbModal, which has all the properties, including 'dismiss' and 'open'. 
    }
    

    如果您需要对表单进行验证,那么我将传入 ngForm,在本例中为“f”。我只发现检查表单是否已提交很有用。除此之外,我使用我在组件中定义的表单组。

    【讨论】:

    • 我不太明白你的意思,你能给我详细的代码吗?
    猜你喜欢
    • 2021-08-02
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 2018-07-15
    相关资源
    最近更新 更多