【问题标题】:The formBuilder.group() cant get data from @input in angular8formBuilder.group() 无法从角度 8 中的 @input 获取数据
【发布时间】:2021-02-11 03:20:46
【问题描述】:

我正在尝试实现一个编辑表单,该表单显示它从数据库中获取的值数据,但问题是当我尝试将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
    });
  }

【问题讨论】:

    标签: javascript angular2-forms


    【解决方案1】:

    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]
     });
    }
    

    【讨论】:

      【解决方案2】:

      您必须创建表单控件。为了更容易阅读和维护,我还会做一些不同的事情。

      最佳做法是在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)
           });
        }
      

      应该这样做!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-06
        • 2018-11-20
        • 2018-08-15
        • 1970-01-01
        • 2021-07-02
        • 2020-01-16
        • 2015-08-28
        • 1970-01-01
        相关资源
        最近更新 更多