Angular-在表单上提交条件上显示引导模式



i具有基于模型驱动方法的角5形式。我已经验证了,并进行了API调用。API调用返回值后,我设置了指示器truefalse。基于此返回的值,我想显示一个标准模式,指示结果,并在表单内容成功时清除表单内容。以下是我的代码:

signup.component.html

<form [formGroup]="myForm" novalidate (ngSubmit)="register(myForm.value)" id="signUpForm" role="form">
  <div class="row">
    <div class="col-lg-12 col-md-12">
      <div class="form-group">
        <input type="email" formControlName="email" placeholder="Enter Email..." class="form-control" aria-required="true">
      </div>
    </div>
  </div>
</form>
....
<div class="modal fade" [hidden]="!myForm.valid">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">User Register</h5>
      </div>
      <div class="modal-body">
        <p>Signup done!</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

在我的signup.component.ts中:

export class SignupComponent implements OnInit {
  public myForm: FormGroup;
  public submitted: boolean = false;
  constructor(...
    private formBuilder: FormBuilder) { }
  ngOnInit() {
    this.myForm = this.formBuilder.group({
      email: ['', [<any>Validators.required, <any>Validators.pattern("[^ @]*@[^ @]*")]]
    });
  }
  register(model: User) {
    this.authService.register(model.email)
      .subscribe(
      data => {
        this.submitted = true;
      },
      error => {
        this.submitted = false;
      });
  }
}

再次问题:1-即使值为真,模态也不会弹出。2-一旦值确实变为真,我希望将表单重置。

用于从组件打开bootrap模式您需要声明

declare var $;

外部组件。然后,当成功提交后要显示模态时,请使用ViewChild

import { ElementRef, ViewChild } from '@angular/core';
// ...
@ViewChild('someModal') someModal:ElementRef;
register(model: any) {
  this.submitted = true;
  // ...
  $(this.someModal.nativeElement).modal('show'); 
}

对于从表单中删除值,您只需致电this.myForm.reset()

Stackblitz

您也可以考虑使用 ng-bootstrap :)

上面的答案在Angular 9.1.12

上对我无效

我在项目中确实还有很多其他依赖项和东西,因此可能是我看不到的一些问题。这对我有用:

  1. private modalService: NgbModal添加到您的构造函数

  2. 添加您的表单变量,例如<ng-template #askApprovalModal >

  3. 将您的元素访问者(如@ViewChild('askApprovalModal') askApprovalElementRef:ElementRef;)添加到.TS类

  4. 添加一个按钮以触发条件以打开模态 <button (click)="f() > </button>"

  5. 使用ngbmodal这是发生魔术的地方,将此功能添加到您的.TS类

    open(content) {
     this.modalService.open(content);
    }
    
  6. 将句柄添加到您的点击事件

    f(){
     this.open(this.askApprovalElementRef)
    }
    

您的模态CSS将由您结束。

最新更新