# Add an Unsaved Changes Guard to an Angular App

Yes. An agent adds a canDeactivate guard that asks before leaving a dirty editor or settings form, plus a beforeunload warning, with Vitest specs, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-unsaved-changes-guard/angular/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the routes and the forms before writing a guard. In an app shaped like realworld-apps/angular-realworld-example-app, `package.json` runs Angular 21.2.12 with `rxjs` 7.8.2, tests with `vitest` through `@analogjs/vite-plugin-angular`, end-to-end tests with Playwright, and formats with Prettier; the workflows install with `bun install` and run `bun run format:check` and the Playwright suite. `src/app/app.routes.ts` is a standalone route table with a functional `requireAuth` guard built on `inject(UserService).isAuthenticated`, applied through `canActivate` to `settings` and to the `editor` and `editor/:slug` children, each loaded with `loadComponent`. No route has `canDeactivate`.

`features/article/pages/editor/editor.component.ts` holds `articleForm`, a `FormGroup` of `title`, `description` and `body`, a `tagList` signal and a `tagField` control, patches the form from the loaded article in `ngOnInit`, and in `submitForm` navigates to `/article/:slug` on success. `features/settings/settings.component.ts` holds `settingsForm` with `image`, `username`, `bio`, `email` and `password`, patched from `getCurrentUserSync()`. In both, a user who types and then clicks a header link loses the text with no warning.

The agent adds `src/app/core/guards/unsaved-changes.guard.ts`: an interface `HasUnsavedChanges` with `hasUnsavedChanges(): boolean`, and a `CanDeactivateFn<HasUnsavedChanges>` that returns `true` when the component reports no changes and otherwise returns the answer of a `confirm` dialog through a small injectable `ConfirmService`, so a spec can replace it. `EditorComponent` implements the interface as `articleForm.dirty || tagList changed since load`, cleared by a `saved` flag that `submitForm` sets before it navigates; `SettingsComponent` does the same on `settingsForm`, calling `markAsPristine()` after the `patchValue` in `ngOnInit` so a loaded profile does not count as a change. Both components get a `@HostListener('window:beforeunload')` that sets `returnValue` when there are unsaved changes, which covers reload and tab close. `app.routes.ts` adds `canDeactivate: [unsavedChangesGuard]` to the two editor routes and to `settings`.

Specs follow `features/article/services/articles.service.spec.ts`, which initialises `TestBed` with Vitest: `unsaved-changes.guard.spec.ts` covers a clean component passing, a dirty one blocked when the confirm answers false, and allowed when it answers true, and `editor.component.spec.ts` covers the flag flipping after a successful submit so the navigation in `submitForm` is not blocked by its own guard. The agent runs `bun run test`, `bun run format:check` and `bun run build`, then starts the app, types in the editor, clicks Home, and captures the dialog for the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add an unsaved changes guard to this Angular app and open a pull request. Read package.json, vitest.config.ts, src/app/app.routes.ts, src/app/features/article/pages/editor/editor.component.ts and its template, src/app/features/settings/settings.component.ts and its template, src/app/core/auth/services/user.service.ts and src/app/features/article/services/articles.service.spec.ts first. Add src/app/core/guards/unsaved-changes.guard.ts with a HasUnsavedChanges interface and a functional CanDeactivateFn that passes a clean component and otherwise asks an injectable ConfirmService wrapping window.confirm. Implement hasUnsavedChanges on EditorComponent from articleForm.dirty and a changed tagList, cleared by a saved flag set in submitForm before navigation, and on SettingsComponent from settingsForm.dirty after markAsPristine following the patchValue in ngOnInit. Add a window:beforeunload HostListener to both that sets returnValue when there are unsaved changes. Register canDeactivate on the editor, editor/:slug and settings routes. Add unsaved-changes.guard.spec.ts and editor.component.spec.ts with TestBed in the existing Vitest style covering clean, dirty and confirmed cases and the saved flag after submit. Run bun run test, bun run format:check and bun run build, then start the app, type in the editor, navigate away and include a screenshot of the dialog in the pull request. Do not change the auth guard or the forms' validators.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that adds `src/app/core/guards/unsaved-changes.guard.ts`, a `ConfirmService` beside it, and two spec files, and changes `app.routes.ts`, `editor.component.ts` and `settings.component.ts`. The description shows the Vitest summary with the new specs, a clean Prettier check, the production build output, and a screenshot of the browser's confirm dialog over the editor after a header link was clicked.

On a repository with these workflows, the pull request runs the Prettier check and the Playwright suite. The end-to-end specs fill forms and submit them, which sets the `saved` flag before navigation, so they pass unchanged; a spec that navigates away mid-edit would now meet a dialog, and the agent reads the Playwright files to confirm none does.

A reviewer checks that the `saved` flag is set before `router.navigate` and not after, so a successful submit never triggers the dialog, that a tag added with `addTag` counts as a change, and that the `beforeunload` text is the browser's own, since modern browsers ignore a custom message. Then they decide whether the comment box on the article page deserves the same guard, which the pull request does not add.

## Run it on every new form in the app

Send one `POST /o/{org}/sessions` per form or feature, naming the component and its route in `input`, and each run reads that form's controls and submit path before implementing `hasUnsavedChanges`, so a form built on signals rather than `FormGroup` compares a snapshot instead of reading `dirty`, and a form inside a dialog gets the guard on its close action rather than a route.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn finishes, with the `session_url` to read the pull request link from, so a handler on your server can post it where that feature's owners review.

## Why run it on Rush?

A deactivate guard has one bug everyone ships once: it fires on the navigation that follows a successful save. The agent writes that case as a spec, runs the suite, and then drives the real app in its sandbox's browser, typing, saving and navigating, and keeps the test output and the screenshot in the run's record, so the pull request shows the dialog appearing when it should and not when it should not.

An Angular build and a Vitest run through the Analog plugin take a while on a laptop, and a Playwright suite longer. In Rush they run in the agent's own sandbox before the pull request opens, and the same request body applies to every Angular app a team maintains, each guarded in its own run.

## Frequently asked questions

### Why a functional guard instead of a class?

The route table already uses a functional `requireAuth` guard with `inject`, and Angular 21 treats functional guards as the standard form. The new guard follows the same shape, so the two read alike in `app.routes.ts`.

### Why wrap window.confirm in a service?

So the specs can replace it. `TestBed` provides a fake `ConfirmService` that answers true or false, which lets the guard be tested without a real dialog. The production service calls `window.confirm` and nothing else.

### Will the Playwright tests start seeing the dialog?

Only a test that edits a form and navigates away without saving would. The agent reads the Playwright specs and reports in the pull request that each one submits before leaving; if one does not, it adds a dialog handler to that spec rather than weakening the guard.

### Does it cover closing the tab?

Yes. Both components listen for `window:beforeunload` and set `returnValue` when there are unsaved changes, which makes the browser show its own leave-page prompt. The text of that prompt is the browser's; custom messages are ignored.

## More Angular jobs

- [Dockerize an Angular App](https://getrush.ai/run/dockerize-app/angular/)
- [Find Dead Code in an Angular App](https://getrush.ai/run/find-dead-code/angular/)
- [Fix a Failing CI Build in an Angular App](https://getrush.ai/run/fix-failing-ci/angular/)

## More jobs like this: Hand off a long task

- [Add User Registration to a CodeIgniter App](https://getrush.ai/run/add-user-registration/codeigniter/)
- [Add User Registration to a Fastify App](https://getrush.ai/run/add-user-registration/fastify/)
- [Add User Registration to a Vapor App](https://getrush.ai/run/add-user-registration/vapor/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
