简体   繁体   English

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

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

I'm trying to implement a edit form that displays value data that it gets in from the db but the problem is that when I try to use formGroup with formBuilder I cant put my @INPUT data in the constructor I get undefined data.我正在尝试实现一个编辑表单,该表单显示它从数据库中获取的值数据,但问题是当我尝试将formGroupformBuilder一起使用formGroup ,我无法将 @INPUT 数据放入构造函数中,但我得到了未定义的数据。

How can I use the @input data in the formbuilder constructor?如何在 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
    });
  }

You have to create the form controls.您必须创建表单控件。 I would also do a couple things different to be easier to read and maintain.我也会做一些不同的事情来更容易阅读和维护。

Is best practice to initiate the form on OnInit instead of the constructor.最佳做法是在OnInit而不是构造函数上启动表单。 When a class is instantiated it will first run the constructor and then OnInit.当一个类被实例化时,它将首先运行构造函数,然后是 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)
     });
  }

That should do it!应该这样做!

Iconio is correct - you should create a function that sets up your form once the component has loaded. Iconio 是正确的 - 您应该创建一个函数来在组件加载后设置表单。

There is no need to declare a new FormControl for every field on your form though.不过,无需为表单上的每个字段声明一个新的 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]
 });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM