i具有基于模型驱动方法的角5形式。我已经验证了,并进行了API调用。API调用返回值后,我设置了指示器true
或false
。基于此返回的值,我想显示一个标准模式,指示结果,并在表单内容成功时清除表单内容。以下是我的代码:
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
上对我无效我在项目中确实还有很多其他依赖项和东西,因此可能是我看不到的一些问题。这对我有用:
将
private modalService: NgbModal
添加到您的构造函数添加您的表单变量,例如
<ng-template #askApprovalModal >
将您的元素访问者(如
@ViewChild('askApprovalModal') askApprovalElementRef:ElementRef;
)添加到.TS类添加一个按钮以触发条件以打开模态
<button (click)="f() > </button>"
使用ngbmodal这是发生魔术的地方,将此功能添加到您的.TS类
open(content) { this.modalService.open(content); }
将句柄添加到您的点击事件
f(){ this.open(this.askApprovalElementRef) }
您的模态CSS将由您结束。