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.

2
  • Have you tried databinding: [value]="categoryTitle"? Commented Oct 29, 2018 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. Commented Oct 29, 2018 at 16:43

1 Answer 1

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)])
  })
}
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.