Reputation: 2329
I want to submit a small form through Angular 5. There is a file upload field within the form. In the .ts file, I have imported the ngForm as below
import { NgForm } from '@angular/forms';
and for the testing purpose, I just placed a console text in the form submission method as below:
onSubmit(form : NgForm) {
console.log("form submitted !");
}
The form in the html view is as under:
<form method="post" (ngSubmit)="mydocumentFrm.form.valid && onSubmit(mydocumentFrm)" #mydocumentFrm="ngForm">
<input class="form-control-file border" type="file" id="filename" required ngModel name="filename" #filename="ngModel">
<small class="form-text text-muted">(Image, PDF or Word doc)</small>
<div *ngIf="mydocumentFrm.submitted && filename.invalid" class="invalid-feedback">
<div *ngIf="filename.errors.required">Field is required</div>
</div>
<div class="form-group">
<button class="btn btn-secondary" type="submit">Upload</button>
</div>
</form>
I see that the form is not been validated if I did not select any file OR when I clicked on the submit button by selecting an image file, the console text is not appearing. However, no error occurred at the console screen.
Upvotes: 0
Views: 58
Reputation: 392
You can also disable your button and verify if form is valid in your ts file.
<button class="btn btn-secondary" [disabled]="!mydocumentFrm.valid" type="submit">Upload</button>
In yours ts file :
onSubmit(form : NgForm) {
if (form.valid) {
console.log("form submitted !");
}
}
Upvotes: 0
Reputation: 43
Remove mydocumentFrm.form.valid from (ngSubmit) line. rewrite this like (ngSubmit)="onSubmit(mydocumentFrm)"
Upvotes: 1