I have a Angular 5 form based on the Model Driven Approach. I have validated and stuff and make the API call. Once the api call returns a value, I set an indicator true or false. Based upon this returned value, I want to show a standard modal indicating the result and also clear the form contents if it was successful. Below is my code:
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>
In my 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;
});
}
}
So the problems again: 1 - The modal doesn't popup even if the value is true. 2 - Once the value does become true, I want the form to be reset.
For opening bootrap modal from component you need to declare
declare var $;
outside component. Then when you want to display the modal after successfully submitting, use ViewChild and
import { ElementRef, ViewChild } from '@angular/core';
// ...
@ViewChild('someModal') someModal:ElementRef;
register(model: any) {
this.submitted = true;
// ...
$(this.someModal.nativeElement).modal('show');
}
As for removing the values from form, you can just call this.myForm.reset()
You could also consider using ng-bootstrap :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With