4

I have made a reusable component that has a reactive form group. I have 2 input properties "name" and "Description" and I am iterating the component with ngFor setting these input properties.

Unfortunately, even if I set my start/default value in the form control group to the input properties, when I click submit angular reads those 2 input properties as 'null' instead of the value being set via the input property.

Form Group + Input Properties:

  @Input() categoryID;
  @Input() categoryTitle;
  @Input() categoryDescription; 

  categoryForm = new FormGroup({
    categoryTitle: new FormControl(this.categoryTitle, [Validators.minLength(3), Validators.maxLength(50)]),
    categoryDescription: new FormControl(this.categoryDescription, [Validators.minLength(5), Validators.maxLength(200)])
  })

Submit function:

this.startLoading();

this.admin.updateCategory(this.categoryForm.value.categoryTitle, this.categoryForm.value.categoryDescription, this.categoryID)

If I try to submit directly the value of the input property that works but then if I make a modification to the form I'm no longer submitting the changed value so that doesn't make sense.

SebastianG
  • 8,563
  • 8
  • 47
  • 111
  • Have you tried databinding: `[value]="categoryTitle"`? – Aluan Haddad Oct 29 '18 at 16:37
  • @AluanHaddad I am doing that already on the markup and it works and it's all fine but when I click submit in the actual controller the default value in the form is not the same as the default valued displayed on the markup and are not necessarily synced. The solution provided below worked however. – SebastianG Oct 29 '18 at 16:43

1 Answers1

3

You should create the FormGroup once the component view is initialized. So you can implement AfterViewInit and put the following code in ngAfterViewInit function.

ngAfterViewInit(){
  this.categoryForm = new FormGroup({
    categoryTitle: new FormControl(this.categoryTitle, [Validators.minLength(3), Validators.maxLength(50)]),
    categoryDescription: new FormControl(this.categoryDescription, [Validators.minLength(5), Validators.maxLength(200)])
  })
}
Sunil Singh
  • 11,001
  • 2
  • 27
  • 48
  • Damn! thank you -- I have done this via ngOnInit and it seems to have worked as well, easy solution in the end after so much hassle! – SebastianG Oct 29 '18 at 16:42