Search code examples
javascriptangular2-forms

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.

How can I use the @input data in the formbuilder constructor?

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

Solution

  • 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. When a class is instantiated it will first run the constructor and then 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!