>我有一个角度材料对话框,里面有一个模板驱动的表单。当我单击提交按钮时,它运行良好,但是当我单击取消按钮时,也会调用 onSubmit() 函数。如何防止这种情况发生? 这是我的代码片段
// 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>
显式放置type="button"
以避免按钮三重输入表单
<button mat-button type="button" (click)="onNoClick()">Cancel</button>
您可以在此处查看规范 请注意,除非另有说明,否则默认行为是submit
。
模板更改:
(click)="onNoClick($event)"
组件更改:
onNoClick(event:any): void {
event.stopPropagation();
........//Your existing code
this.dialogRef.close();
}
要了解更多信息,请阅读:https://javascript.info/bubbling-and-capturing
在我的模板中,我从<button mat-button (click)="onNoClick()">Cancel</button>
更改为<button mat-button [mat-dialog-close]="data" (click)="onNoClick()">Cancel</button>
不知何故,它阻止了onSubmit()函数被调用。
只需从取消按钮中删除(click)="onClick()"
即可。
这将解决您的问题