0

I need to disable some fields based on my angular form. I am trying to disable the DOM elements in component class because many html tags are customized and so disabled attribute cannot be used there. The way I am doing this is using @ViewChild/@ViewChildren in my component and disabling in ngAfterViewInit(). I am not able to disable the elements which are inside ngIf in html. Below is the code: Html:

<div *ngIf="displayAdvOpt">
        <div class="card-title">Rules</div>
        <abc-select-field
          #rule
          width="100%"
          label=" "
          formControlName="_rules"
          [options]="rules"
        ></abc-select-field>
<div>

Component class:

@ViewChildren('rule') ruleSelect;

When logging ruleSelect in component class, it shows that is a QueryList and not a FormControl, as is the case for the elements not inside ngIf. Due to this, I am not able to do ruleSelect.control.disable() to make it disabled in html. I am doing these in ngAfterViewInit(). Please let me know how can I disable a QueryLst or if there is any other way.

Abhinash Jha
  • 165
  • 1
  • 3
  • 17

3 Answers3

1

@Abhinash, you can not acces to any element if is not in the screen. As you has the element under a *ngIf you need condition becomes true and "after Angular repaint", enable/disable... so, in general

this.condition=true;
setTimeout(()=>{
   this.ruleSelect.....
})

But your abc-select-field, has a FormControl in any way and the FormControl exist even the abc-select-field is not in screen, so if you makes that the elements are disabled depending if the control is disabled

Eliseo
  • 50,109
  • 4
  • 29
  • 67
0

In order to disable the select field, you don't need to know neither that 'distinction' (QueryList/Control) nor a 'local reference' (#rule) :

Simply, in the code you want to disable, you just need to do this:

this.form.get('_rules').disable();
// or this.form.constrols['_rules'].disable();

Similarly, when you want to re-enable it you can use:

this.form.get('_rules').enable();
0

Below is the workaround I tried.

<div *ngIf="displayAdvOpt">
            <div class="card-title">Rules</div>
            <abc-select-field
              #rule
              width="100%"
              label=" "
              formControlName="_rules"
              [options]="rules"
              on-mouseover="isDisabled()"
            ></abc-select-field>
    <div>

In component class:

@ViewChild('rule') ruleSelect;
isDisabled() {
    if (this.showChanges){
      this.ruleSelect.control.disable();
    }

I see that in ngAfterViewInit(), ruleSelect is a QueryList but in isDisabled() the method called after on-mousehover, it is coming as AbcSelectFieldComponent and so I can call .control.disable() on it. The only reason I can think of is this- https://stackoverflow.com/a/55610325/4464806 Anymore suggestions are welcome!!

Abhinash Jha
  • 165
  • 1
  • 3
  • 17