I have one angular material dialog box and inside that there is one template driven form. It is working well when I click on submit button however when I click on cancel button then also onSubmit() function is getting called. how to prevent that? this is my code snippet
// ts file
export class RejectPopupComponent implements OnInit {
submitted:boolean=false;
comment: string;
loanID: string;
createdDate: string;
constructor(
private dataService: DataService,
public dialogRef: MatDialogRef<RejectPopupComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.dataService.loanIdSource.subscribe(loanID => (this.loanID = loanID));
console.log(this.loanID);
this.dataService.applicationDateSource.subscribe(
applicationDate => (this.createdDate = applicationDate)
);
console.log(this.loanID, this.createdDate);
}
onNoClick(): void {
this.dialogRef.close();
}
onSubmit(form:any){
console.log('hello')
console.log(form);
const statusDecisionInput = { loanID: "", createdDate: "", approverAction: "Rejected", reasonToReject: '' };
statusDecisionInput.loanID = this.loanID;
statusDecisionInput.createdDate = this.createdDate;
statusDecisionInput.reasonToReject = form.reasonToReject;
console.log(statusDecisionInput);
this.submitted=true;
}
ngOnInit() {}
}
<form #f="ngForm" (ngSubmit)="onSubmit(f.value)">
<div mat-dialog-content>
<p>Why are you rejecting?</p>
<textarea matInput rows="10" cols="38" placeholder="Leave a comment" name="reasonToReject" ngModel required></textarea>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">Cancel</button>
<button mat-button class="submit-button" type='submit'
[disabled]="f.invalid" cdkFocusInitial (click)="onNoClick()">Submit</button>
</div>
</form>
You may want to add a 'reset' or 'cancel' button to your form. When doing so, be wary of the type property passed to your <button/> . This can cause all buttons within your form to trigger onSubmit .
Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.
please use onsubmit attribute in the form element and write a javascript function to return false when there is any error.
Put type="button"
explicitly to avoid button trigerring a form submission
<button mat-button type="button" (click)="onNoClick()">Cancel</button>
You can check the spec here Note that the default behaviour is submit
unless specified otherwise.
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