简体   繁体   中英

Angular2 Reactive Forms disable elements in form group

I have a reactive form setup in my component that allows a user to edit user data within the form.

On this form, there are table rows and at the end of each row is a checkbox that disables or enables all the inputs in that row. The user essentially enables that group of input data to fill out.

Here is my form group:

slice3: this.fb.group({
    shitStatus: { value: 0 },
    hour_start: { value: '1', disabled: true },
    minute_start: { value: '00', disabled: true },
    period_start: { value: 'AM', disabled: true },
    hour_end: { value: '1', disabled: true },
    minute_end: { value: '00', disabled: true },
    period_end: { value: 'AM', disabled: true },
    days: this.fb.group({
        day_Su: { value: '', disabled: true },
        day_M: { value: '', disabled: true },
        day_Tu: { value: '', disabled: true },
        day_W: { value: '', disabled: true },
        day_Th: { value: '', disabled: true },
        day_F: { value: '', disabled: true },
        day_Sa: { value: '', disabled: true }
    })
})

I have a function that toggles all the elements in this form group when they check or uncheck the box:

toggleSlice(slice) {

  if (this.transitionForm.get('shift.slice' + slice).disabled) {
    this.transitionForm.get('shift.slice' + slice).enable();
  } else {
    this.transitionForm.get('shift.slice' + slice).disable();
  }

}

My issue is due do shiftStatus being part of the form group, it is disabling the toggle button as well which then prevents me from ever turning this set of elements back on.

Is there any way to use some type of operator in here that allows me to say Disable everything in the shift.slice except for a specific input?

In jQuery for example, I could do something like :not("blah") to say apply this logic to everything except this input.

Can anything be done with javascript that will allow me to disable all these elements within a form group except for one that I specify?

The easiest solution I see is to disable all form controls and then just enable that one form control, I can't think about a better way. Here's just pseudo code:

if (this.myForm.get('group').disabled) {
  this.myForm.get('group').enable();
} else {
  this.myForm.get('group').disable();
  this.myForm.get('group.shiftStatus').enable()
}

What you'd also maybe want is to actually store this form control paths to variables, so that you don't need to call get all the time, but that is just a suggestion :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM