@ViewChild以子组件形式返回未定义的引用

时间:2019-09-20 18:16:27

标签: angular angular-forms

我在父组件中有一个表单,该表单会将数据作为输入属性传输到子组件,而子组件具有读取此数据并用此数据预填充其表单的表单,以作为编辑用户配置文件的方式。在我尝试使用传输的数据设置输入字段的那一行中,chrome返回了一个控制台错误,指出它无法读取未定义的setValue属性。代码有什么问题?

以下是代码:

 components: {
    AddEducationForm,
    MainButton,
    EducationItem
  },

子组件:

 [1]: https://jsfiddle.net/trilokvallamkonda/cLgzf21y/13/

子组件模板:

this.eForm.setValue({
        firstname: this.employee.user.firstname,
        lastname: this.employee.user.lastname,
        email: this.employee.user.email
      });

1 个答案:

答案 0 :(得分:3)

// query results available in ngOnInit
@ViewChild('f', {static: true}) eForm: NgForm;


ngAfterViewInit() {

this.eForm.setValue({
    firstname: this.employee.user.firstname,
    lastname: this.employee.user.lastname,
    email: this.employee.user.email
  });

}

https://angular.io/guide/static-query-migration