formBuilder.group() 无法从角度 8 中的@input 获取数据

The formBuilder.group() cant get data from @input in angular8

我正在尝试实现一个显示从数据库中获取的值数据的编辑表单,但问题是当我尝试将 formGroupformBuilder 一起使用时,我无法将我的构造函数中的@INPUT 数据我得到未定义的数据。

如何在 formbuilder 构造函数中使用@input 数据?

 export class EditModalComponent implements OnInit {
  checkoutForm;
  @Input() product //this is the data from the father component
  closeResult = '';

  ngOnInit() {

  }

  constructor(private modalService: NgbModal,
    private formBuilder: FormBuilder) {
    this.checkoutForm = this.formBuilder.group({
      imageURL: this.product.imageURL,// i get undefined
      name: this.product.name,// i get undefined
      category: this.product.category,// i get undefined
      price: this.product.price,// i get undefined
    });
  }

您必须创建表单控件。我还会做一些不同的事情,以便于阅读和维护。

是在 OnInit 而不是构造函数上启动表单的最佳做法。 当实例化 class 时,它将首先 运行 构造函数,然后是 OnInit。

  ngOnInit() {
     this.initForm();
  }

  initForm() {
     this.checkoutForm = this.formBuilder.group({
         imageURL: new FormControl(this.product.imageURL),
         name: new FormControl(this.product.name),
         category: new FormControl(this.product.category),
         price: new FormControl(this.product.price)
     });
  }

应该可以!

Iconio 是正确的 - 您应该创建一个函数来在组件加载后设置您的表单。

虽然没有必要为表单上的每个字段都声明一个新的 FormControl。

ngOnInit() {
    this.populateForm();
}

populateForm() {    
  this.checkoutForm = this.formBuilder.group({
     imageURL: [this.product.imageURL],
     name: [this.product.name],
     category: [this.product.category],
     price: [this.product.price]
 });
}