简体   繁体   中英

Dynamically disable a dropdown of reactive form

I'm trying disable a dropdown built with ul and li i have to use ui and li instead of select for requirement inside a reactive form.

Html

<ul data-dropdown data-value class="bx--dropdown" tabindex="0">
     <li class="bx--dropdown-text">Validation type</li>
     <li>
       <ul class="bx--dropdown-list">
        <li data-option [attr.data-value]="input" class="bx--dropdown-item"   *ngFor="let input of validationTypes;">
         <a class="bx--dropdown-link" href="javascript:void(0)" tabindex="-1">{{input}}</a>
        </li>
      </ul>
   </li>
</ul>

ts

let fieldSetGroup = <FormArray>this.createTemplateForm.get("fieldSets");
        fieldSetGroup.push(this.fb.group({
            key: ["", Validators.required],
            "type": ["", Validators.required],
            mandatory : ["", Validators.required],
            validationType: [""]
}));
let fg  = <FormGroup> fieldSetGroup.controls[id];
if (fg.controls["key"] === "Apple") {
  fg.controls["validationType"].disable();
}

tried adding formControlName on both ul and li...didnt work...How to handle this case?

you have 2 options either use reactive form or use css class

for useing reactive form add formControlname to your component

<ul data-dropdown data-value class="bx--dropdown" tabindex="0" formControlName="validationType">
     <li class="bx--dropdown-text">Validation type</li>
     <li>
       <ul class="bx--dropdown-list">
        <li data-option [attr.data-value]="input" class="bx--dropdown-item"   *ngFor="let input of validationTypes;">
         <a class="bx--dropdown-link" href="javascript:void(0)" tabindex="-1">{{input}}</a>
        </li>
      </ul>
   </li>
</ul>

and add below code in your method (where you WANT TO disable it)

const ctrl = this.fg.get('validationType');
  ctrl.disable();

To achice this using css
add this in your component css

.disabled{
    pointer-events:none;
    opacity:0.4;
  }

and in ur html add this calss to your element

 <ul data-dropdown data-value class="bx--dropdown" tabindex="0" [class.disabled]="fg.invalid">
     <li class="bx--dropdown-text">Validation type</li>
     <li>
       <ul class="bx--dropdown-list">
        <li data-option [attr.data-value]="input" class="bx--dropdown-item"   *ngFor="let input of validationTypes;">
         <a class="bx--dropdown-link" href="javascript:void(0)" tabindex="-1">{{input}}</a>
        </li>
      </ul>
   </li>
</ul>

Please replace fg.invalid with your validetion condition

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