Reputation: 171
I have a dashboard where I have 4 different routes. When login user will be redirected to a route /fillForm
. Until the user fills the form and submit, it should be force redirect to same route. How can I achieve this case? I tried using CanDeactivate, but don't know how can I do the usage in my fillForm.ts
Note: I don't want to hide the routes and display them on submit.
<li>
<a mat-button routerLink="/fillForm" routerLinkActive="mat-accent">Details</a>
</li>.
<li>
<a mat-button routerLink="/manage" routerLinkActive="mat-accent">view and mange posts</a>
</li>.
<li>
<a mat-button routerLink="/common" routerLinkActive="mat-accent">everyone</a>
</li>.
app routing module
{ path: '/fillForm', component: FillFormComponent, canDeactivate: [CanDeactivateGuard] }
my CanDeactivate.ts
import { Observable } from 'rxjs/Observable';
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return component.canDeactivate();
}
}
html
<form (ngSubmit)="onRegisterSubmit(form)" [formGroup] = "form">
<input type="text" formControlName="username" class="form-control" >
<input type="submit" class="btn btn-primary" value="Submit" [disabled]="!form.valid">
</form>
fillForm.ts
submitted:false,
onRegisterSubmit(form): void {
if(form.valid){
this.submitted=true;
const username = form.value;
// I will navigate to another page
// since field is disabled, we need to use 'getRawValue'
this.form.reset() // reset form to empty
}
}
canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
if(!this.submitted){
//stay on same page
}
}
Upvotes: 0
Views: 754
Reputation: 10979
Use CanDeactivate Router guard, that we he will not be able to navigate away from this page, until you want.
export class CanDeactivateGuard implements CanDeactivate<FillFormComponent> {
public submittedOnce = false;
canDeactivate(component: FillFormComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(component.submitted) {
this.submittedOnce = true;
}
return this.submittedOnce;
}
}
Upvotes: 1