我试图在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 {}
知道如何解决这个问题吗?