title: Getting a NgForm instance from an Angular directive
body: <p>I'm trying to create a behavior where all my forms that are attached to a <code>preventFormChangesLoss</code> directive will behave so that if there are changes to the form (if it's not <code>pristine</code> or <code>submitted</code>), the page shows a warning when the user wants to leave.</p>
  
  <p>For that, I am trying to get my directive to get the NgForm instance my directive is attached to.
  For now, I have </p>
  
  <pre><code>import { Directive, Input, ElementRef, OnInit, AfterViewInit, ViewChild } from '@angular/core';
  import { NgForm } from '@angular/forms';
  
  @Directive({
    selector: '[preventFormChangesLoss]'
  })
  export class PreventFormChangesLoss implements OnInit, AfterViewInit {
    private origin: string = '';
  
    @ViewChild('myForm') form : NgForm;
  
    constructor(private elRef: ElementRef) {
      console.log(this.elRef);
    }
  
    ngOnInit() {
      console.log(this.elRef, this.form);
    }
  
    ngAfterViewInit() {
      console.log(this.elRef, this.form); // shows the native element, + 'undefined'
    }
  }
  </code></pre>
  
  <p>And I use it with </p>
  
  <pre><code>&lt;form preventFormChangesLoss #myForm="ngForm"&gt;
  ...
  &lt;/form&gt;
  </code></pre>
  
  <p>Unfortunately, this does not work, and I also would like my directive to get the NgForm instance without having to do the <code>#myForm="ngForm"</code> part, so that I can name my forms however I want and keep this behavior separate.</p>
  
  <p>How can I do that, and can someone point me to the right place in the docs?</p>