Reputation: 727
I am creating a form in ionic2 in which fields changes as per categories changed by user dynamically.
if a field category is A is selected
then some fields such as start_date and time are required
but for category B only start_date is required
and for C both are not required.
I am using FormBuilder
in ionic2 and validating like:
this.logForm = formBuilder.group({
'start_date': ['', Validators.compose([Validators.maxLength(30),
Validators.required])],
'time': ['', Validators.compose([Validators.maxLength(30),
Validators.required])],
});
I am getting the selected category in an alert result like this:
category(){
var options = {
title: 'Choose a task category',
inputs: [],
message: 'Which category do you like?',
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
},
{
text: 'Ok',
handler: data => {}
}
]
}
}
In the handler of 'Ok' I can successfully retrieve the selected category.
So my question is how can i apply validation dynamically as per the category selected by user in app.
Upvotes: 1
Views: 549
Reputation: 29614
You could try using setControl function in the formgroup api.
For example in the data handler of category:
()=>{
this.logForm.setControl('start_date',new FormControl('',Validators.required);
}
API of formControl here
Upvotes: 1