title: Angular: Got error on using viewchild with form of ERROR TypeError: Cannot read property 'dirty' of undefined
body: <p>I am trying to get the form element using viewchild in angular 5 app as illustrated below, but got error: TypeError: Cannot read property 'form' (pointing to this.campaignForm.form) of undefined.</p>
  
  <pre><code>@Component({
    selector: 'form-child',
    template: 
      `&lt;div ngif="show"&gt;
        &lt;form #campaignForm="ngForm"&gt;
          &lt;input type="text" [ngModel]='data.input' (ngModelChange)='updateMe()' name='input' required/&gt;
        &lt;/form&gt;
      &lt;/div&gt;
   `
  })
  export class FormChild implements OnInit, AfterViewInit, AfterViewChange {
    @Input() data: any;
    @Output() valid = new EventEmitter();
    @ViewChild('campaignForm') campaignForm: NgForm;
  
    show = true;
  
    constructor() {
      // console.log('here1');
    }
  
    updateMe() {
      console.log('update me: ', this.campaignForm.form.valid);
    }
  
    ngOnInit() {
      this.campaignForm.valueChanges.subscribe(data =&gt; {
        this.valid.emit(this.campaignForm.form.valid);
      }
  
    }  
  }
  
  @NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ App, FormChild ],
    bootstrap: [ App ]
  })
  export class AppModule {}
  </code></pre>
  
  <p>Any idea how to solve this?</p>