Reputation: 1648
Using model driven forms how can I setValue for a nested formGroup? Without the nested formGroup I can do this as follows:
export class MyComponent {
constructor(
private formBuilder: FormBuilder) {
this.form = formBuilder.group({
id: [],
title: ['', Validators.required],
start_date: ['', Validators.required],
end_date: ['', Validators.required]
});
}
ngOnInit() {
...
this.form.setValue({
id: this.academicTerm.id,
title: this.academicTerm.title,
start_date: this.academicTerm.start_date,
end_date: this.academicTerm.end_date
});
...
}
}
This works fine but if I nest the start and end dates into their own dates
formGroup (for validation ... not shown) then I cannot find a way to set the start and end date values.
export class MyComponent {
constructor(
private formBuilder: FormBuilder) {
this.form = formBuilder.group({
id: [],
title: ['', Validators.required],
dates: formBuilder.group({
start_date: ['', Validators.required],
end_date: ['', Validators.required]
})
});
}
Upvotes: 0
Views: 6689
Reputation: 3342
You can set the date value as follow :
this.form.controls['dates'].setValue({
start_date: '',
end_date: '',
});
or the whole form :
this.form.setValue({
id: '',
title: '',
dates: {
start_date: '',
end_date: ''
}
});
But if you're doing it to set default values just do it when you are building the form instead of using empty values (''
).
Upvotes: 4