Reputation: 9554
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.
Upvotes: 4
Views: 1158
Reputation: 11243
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)])
})
}
Upvotes: 3