簡體   English   中英

formBuilder.group() 無法從 angular8 中的@input 獲取數據

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

我正在嘗試實現一個編輯表單,該表單顯示它從數據庫中獲取的值數據,但問題是當我嘗試將formGroupformBuilder一起使用formGroup ,我無法將 @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而不是構造函數上啟動表單。 當一個類被實例化時,它將首先運行構造函數,然后是 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]
 });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM