Angular:使用带有ERROR TypeError形式的viewchild时出错:无法读取属性' dirty'未定义的

时间:2018-03-21 20:31:54

标签: angular

我试图在angular 5 app中使用viewchild获取表单元素,如下图所示,但是出现错误:TypeError:无法读取属性' form' (指向this.campaignForm.form)未定义。

@Component({
  selector: 'form-child',
  template: 
    `<div ngif="show">
      <form #campaignForm="ngForm">
        <input type="text" [ngModel]='data.input' (ngModelChange)='updateMe()' name='input' required/>
      </form>
    </div>
 `
})
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 => {
      this.valid.emit(this.campaignForm.form.valid);
    }

  }  
}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App, FormChild ],
  bootstrap: [ App ]
})
export class AppModule {}

知道如何解决这个问题吗?

0 个答案:

没有答案