基本上我在表单页面上有一个canDeactivate防护,当表单脏了&没有提交,但是当我确认路由它时它没有被路由&当我提交表格时也是如此。
我在控制台中检查了返回值以确认&它记录为真,但路线保持在同一条路线上。
如果有人可以提供帮助,以下是我的参考代码。
使用Observables:
canDeactivate(): Observable<boolean> | boolean {
if (this.heroForm.form.dirty && !this.heroForm._submitted ){
$('#yourModal').modal('show');
document.getElementById("confirm").onclick = ((e: any) => {
$('#yourModal').modal('hide');
console.log(true);
return true;
});
document.getElementById("cancel").onclick = ((e: any) => {
$('#yourModal').modal('hide');
console.log(false);
return false;
});
}
return true;
}
承诺:
canDeactivate(): Promise<boolean> {
let $modal = $('#yourModal').modal();
return new Promise<boolean>((resolve, reject) => {
document.getElementById("confirm").onclick = ((e: any) => {
$('#yourModal').modal('hide');
resolve(true);
});
document.getElementById("cancel").onclick = ((e: any) => {
$('#yourModal').modal('hide');
resolve(false);
});
$modal.modal("show");
});
}
Update.html
<form (ngSubmit)="saveData(); isClickedOnce = true" #heroForm="ngForm" *ngIf="this.news !== undefined">
<div class="abcd clearfix">
<div class="form-group col-xs-12 col-md-6">
<label for="newsdescription">News Description:</label>
<input type="text" class="form-control" id="news_description" name="newsdescription" placeholder="News Description" [(ngModel)]="this.news.newsdescription">
</div>
</div>
<div class="abcde clearfix">
<div class="form-group col-xs-12 col-md-6">
<label for="formData">News Image (Required):</label><span [hidden]="!togglefile" class="alert alert-danger">
Image is required.
</span><br>
<input #fileInput type="file" id="newsimg" name="newsimg" multiple="true" (change)="fileChange($event)" required="true">
</div>
<!-- Modal -->
<div class="modal fade" id="yourModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Discard unsaved changes ?</h4>
</div>
<div class="modal-body">
<div class="col-xs-12 text-center">
<button type="button" id="confirm" class="btn btn-success" title="OK">Yes</button>
<button type="button" id="cancel" class="btn btn-danger" title="Cancel">Cancel</button>
</div>
</div>
</div>
</div>
</div>
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success" [disabled]="!heroForm.form.valid || togglefile" [class.disabled]="isClickedOnce" title="Save">Save</button>
<button type="button" class="btn btn-danger" (click)="gotoNewss()" title="Cancel">Cancel</button>
</div>
</div>
</form>