Prevent closing browser tab when form is dirty in Angular 2
<p>How to prevent closing browser tab when form is dirty in Angular 2?</p>

<p>My html body contains a component:</p>

<pre><code>  &lt;body&gt;
    &lt;my-app&gt;Loading, please wait...&lt;/my-app&gt;
  &lt;/body&gt;
</code></pre>

<p>which contains a router navigation and a router outlet:</p>

<pre><code>&lt;nav&gt;
 (...)
&lt;/nav&gt;
&lt;router-outlet&gt;&lt;/router-outlet&gt;
</code></pre>

<p>and when the router navigates to the edit page, I have some form there:</p>

<pre><code>  &lt;form #myForm="ngForm"&gt;
    &lt;button pButton type="text" label="Save" (click)="onSave()" [disabled]="!myForm.valid || myForm.pristine"&gt;&lt;/button&gt;
  &lt;/form&gt;
</code></pre>

<p>Now, if the form is not 'pristine', I want to ask for confirmation when the user tries to close the browser tab:</p>

<pre><code>window.onbeforeunload = function() {
   if (form.dirty) {
     return "You have unsaved data changes. Are you sure to close the page?"
   }
}
</code></pre>

<p>How can I access the dirty state of Angular form in canonical way from there? I could register an event to field change on each field and set the global dirty flag, but I'd have to put that code on every from and by every navigation and then maintain that code so that the message stays consistent. Is there any other way to check out if there's an angular form on the page, which is in dirty state?</p>