web-dave / ng-essential-workshop

0 stars 0 forks source link

Guard #20

Open web-dave opened 4 years ago

web-dave commented 4 years ago
web-dave commented 4 years ago

generate


ng g guard fleet/leave
web-dave commented 4 years ago

leave.guard.ts


@Injectable({providedIn: 'root'})
export class LeaveGuard implements CanDeactivate<VehicleNewComponent> {
 canDeactivate(target: VehicleNewComponent) {
   if (!target.isSaved()) {
     return window.confirm('Do you really want to cancel?');
   } else {
     return true;
   }
 }
}
web-dave commented 4 years ago

fleet-routing.module.ts


    {
      path: 'new',
      component: VehicleNewComponent,
      canDeactivate: [LeaveGuard]
    }
web-dave commented 4 years ago

vehicle-new.component.ts


// this.saved needs to be set on Save
  isSaved() {
    return this.saved || !this.form.dirty;
  }
web-dave commented 4 years ago

NEXT