How to disable option in select based on parent context

#1

Hi all,

I’m trying to disable an option within a select input, based on the parent context. I know that repeat.for creates a new bindingContext on the fly and I should be able to access the overrideContext for properties in the parent.

Example: I have a meal planner, a select represents the days of the week, when assigning a meal for a day I want to disable that specific day from the available options.

Please see my example here: https://codepen.io/jmberon/project/editor/XNbqkq#

I’m trying both $parent and also straight access to the override context. Plus im getting some sintax errors in my disabled binding. Has anyone do something like this. Thanks.

2 Likes
#2

I think you are just missing model.bind=“null” on both of the default options? If i select an object and move back to original the button is enabled when it should not be.

https://codepen.io/brandonseydel/project/editor/ZJbPba

2 Likes
#3

Thanks for the taking the time brandon, yes that was definetely a bug. However what I wanted to achieve is to disabled the days from the drppdown that already have been a meal assigned to. So for example if I say Monday I will eat fish … then the Monday option should be disabled in the select afterwards. Do I make sense?

2 Likes
#4

This might help - check the disabled state of ‘Tuesday’ in the drop down, then click the Disable Tuesday to show it disabled.

HTML:

    <template>
      <select>
        <option model.bind="null" selected>Select a day</option>
        <option repeat.for="day of days" disabled.bind="day.isDisabled">${day.name}</option>
      </select>
      <input type="button" click.trigger="disableTuesday()" value="Disable Tuesday" />
      <br />
    </template>

Javascript:

export class App {
  constructor() {
    this.days = [
      { name: "Monday", isDisabled: false },
      { name: "Tuesday", isDisabled: false },
      { name: "Wednesday", isDisabled: false }
    ];
  }

  disableTuesday() {
  // Find the day with the name Tuesday
    for (var i = 0; i < this.days.length; i++) {
      if (this.days[i].name == "Tuesday") {
        this.days[i].isDisabled = true;
      }
    }
  }
}
2 Likes
#5

Here is an example without using a property on the main object.
https://codepen.io/brandonseydel/project/editor/ZJbPba

As @Stuart suggested you could also include something on the object itself so the observer knows when to disable rather than be signaled to do so. To achieve this you would need to store an array of valid meals on each day, days on each meal, or a simple boolean set on load.

1 Like
#6

Adjusting the canEatIt method to also pass in the day will make signaler not required. I updated the pen to reflect these changes after talking with @bigopon.

https://codepen.io/brandonseydel/project/editor/ZJbPba

You can also pass in the array of valid meals to days in this to make sure if that array is changed they are also observed.

1 Like