My goal is to create a select dropdown with options for bmw, audi, and opel. The user can only select one option from the dropdown, but they should also have the ability to select the options that were not chosen using checkboxes.
cars = [
{ id: 1, name: 'bmw' },
{ id: 2, name: 'audi' },
{ id: 3, name: 'opel' }
];
Here's how it should work:
For instance, if the user selects bmw in the dropdown, then two checkboxes for audi and opel should be displayed since those are the remaining options. If the user changes their selection from bmw to something else, the checkboxes should update accordingly to display the available options.
Form setup:
this.firstStepForm = this.fb.group({
cars: [''], // select
models: this.fb.array([]) // checkboxes
});
Setting up checkboxes:
private setupControls(details: any): void {
let control = <FormArray>this.firstStepForm.controls.models;
details.forEach(x => {
control.push(this.fb.group({
id: x.id,
name: x.name
}))
})
Subscribing to changes:
this.firstStepForm.get('cars').valueChanges.subscribe((carId: number)
Check out a simple example on stackblitz
I am currently trying to figure out how to determine the index of the selected car and update/remove the checkboxes accordingly.
Desired Results:
- Checkboxes should display only the options that were not selected in the dropdown
- If the selected value changes, checkboxes should update to show the remaining options.
Queries:
Is there a simpler way to achieve this without using removeAt (FormArray)? Maybe I could use underscoreJs _filter function to filter out values based on the id, but how do I filter out FormArray items based on a specific value (:id)?
let magic = _.filter(arr, function (num) { return num != carId });
console.log('magic: ', magic);