1

I try to make a guard when data and image is not been saved. so when you leave the component and didn't triggered the save button. The user will have to get a warning

Googled followed tutorials

So the Guard works for data fields. But if I change the Image and leave the page then nothing happened.

So this is the canActivateGuard:

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean {

    if(!component.canDeactivate()){
        if (confirm("U heeft nog niet opgeslagen data! Als u dit scherm verlaat worden uw gegevens niet opgeslagen.")) {
          console.log('dirty');

          return true;

        } else {
          console.log('not dirty');

          return false;
        }
    }
    return true;
  }
}

the componentCanActivate:

export abstract class ComponentCanDeactivate {

  abstract  canDeactivate(): boolean;

    @HostListener('window:beforeunload', ['$event'])
    unloadNotification($event: any) {
        if (!this.canDeactivate()) {
            $event.returnValue = true;
        }
    }
}

and the formCanDeactivate:

export abstract class FormCanDeactivate extends ComponentCanDeactivate {

 abstract get form(): NgForm;

 canDeactivate(): boolean {
      return this.form.submitted || !this.form.dirty;
  }
}

And this is for the acutal form:

export class SettingsAccountComponent extends FormCanDeactivate implements OnInit, OnDestroy  {
  private profileSubscription: Subscription;
  profile: AccountProfile;
  currentProfile: AccountProfile;
  selectedFileName: string;
  deletePicture: boolean;
  saving: boolean;
  formErrors: { header: string; messages: string[] }[];
  innerWidth = window.innerWidth;


  @ViewChild( 'form', {static: false} )
  form: NgForm;

and this is for the routing.module:

const settingsRoutes: Routes = [

  {
    path: '',
    component: SettingsNavigationComponent,
    canActivate: [AuthGuard] ,
    children: [
     {path: '', redirectTo: 'account', pathMatch: 'full' },
     {path: 'account', component: SettingsAccountComponent, canDeactivate: [CanDeactivateGuard] },
     {path: 'apparaten' , component: SelfcareComponent, canActivate: [AuthGuard] },
     {path: 'apps' , component: SettingsAppsComponent, canActivate: [AuthGuard] },
     {path: 'indicatiepermissies' , component: SettingsIndicatorPermissionsComponent, canActivate: [AuthGuard] },
     { path: 'algemeen', component: SettingsGeneralComponent, canActivate: [AuthGuard] },
     {path: 'log' , component: SettingsLogComponent, canActivate: [AuthGuard] },
     {path: 'organisatie' , component: SettingsAddOrganisationComponent, canActivate: [AuthGuard] },
    ]
   },
];

That the guard also works for changing the image.

Thank you

mightycode Newton
  • 3,229
  • 3
  • 28
  • 54

0 Answers0