首页 > 解决方案 > 如何在 Angular 5 应用程序中禁用单选按钮

问题描述

我需要通过另一个使用反应式表单/表单组动态生成的外部复选框单击事件来禁用单选按钮。

我的组件代码适用于文本框和下拉列表,但不适用于单选框或复选框

这是生成的代码

    <label _ngcontent-c6="" class="container-vertical"> Dog
    <input _ngcontent-c6="" type="radio" ng-reflect-form-control-name="01cb437e-0015-4c45-9828-fb2d1d" ng-reflect-value="8f77b6e1-2495-4781-9e40-520e94" ng-reflect-name="01cb437e-0015-4c45-9828-fb2d1d" class="ng-untouched ng-pristine ng-invalid"> 


    <label _ngcontent-c6="" class="container-vertical"> Cat
    <input _ngcontent-c6="" type="radio" ng-reflect-form-control-name="01cb437e-0015-4c45-9828-fb2d1d" ng-reflect-value="4102b66c-b8c3-4d41-afcd-5852e4" ng-reflect-name="01cb437e-0015-4c45-9828-fb2d1d" class="ng-untouched ng-pristine ng-invalid"> 

    <label _ngcontent-c6="" class="container-vertical"> Fish
    <input _ngcontent-c6="" type="radio" ng-reflect-form-control-name="01cb437e-0015-4c45-9828-fb2d1d" ng-reflect-value="5dc08818-38b0-4563-8e0a-ce8901" ng-reflect-name="01cb437e-0015-4c45-9828-fb2d1d" class="ng-untouched ng-pristine ng-invalid"> 

模板

<div *ngSwitchCase="'radio'">
           <div *ngFor="let opt of question.options" > <small>radio</small>
               <label class="container-vertical"> {{opt.value}}
                       <input type="radio" 
                              [formControlName]="question.key"  
                              [value]="opt.key" 
                              [(ngModel)]="question.value"
                              (change)="onChangeValue(question.value, previousValue, responseId, question.key, 'radio'); previousValue = question.value" 
                              (focus)="previousValue=question.value"
                              > 


                       <span class="checkmark"></span>
               </label>
           </div> 
       </div>

零件

  private handleQuestionAnswerProvidedStateChange(questionAnswerProvidedState:QuestionAnswerProvidedStateDataModel)
 {

   var formControlNameReference = questionAnswerProvidedState.QuestionId.substring(1,30);
//  ???????????? need help here ... how to get reference of radio button to disable it

  if(questionAnswerProvidedState!=null)
  {
    var elementReference = <HTMLInputElement> document.getElementById(questionAnswerProvidedState.QuestionId);
    if(questionAnswerProvidedState.AnswerNotProvided == true)
    {
      elementReference.disabled = true;
      elementReference.value = "";
      elementReference.classList.add("disableInput");
    }
    else if(questionAnswerProvidedState.AnswerNotProvided == false)
    {
      elementReference.disabled = false;
      elementReference.classList.remove("disableInput");
    }
  } 
}

标签: angulartypescriptradio-button

解决方案


<input type="radio" [(ngModel)]="radioButtonVisibility" [attr.disabled]="flag ? '' : null" 
       formControlName="radioButtonVisibility"/>

使用上述属性[attr.disabled]。如果变量标志包含任何值,则单选按钮将被禁用。如果变量标志是,null那么单选按钮将被启用。标志值必须根据要求设置为空或非空。


推荐阅读