首页 > 解决方案 > 单击时禁用单选按钮

问题描述

我有一个不同答案的表格。我的表单控件之一是单选按钮。当我单击此单选按钮之一时,所有其他单选按钮都会启用。

 <form [formGroup]="formAnswers">
                      <!-- body risposte -->
                      <div *ngFor="let answer of questions.answers; let n = index;" class="row mb-1 border-bottom">
                        <!-- checkbox -->
                        <div
                          class="col-xs-1 col-sm-1 col-md-1 col-lg-1 text-left form-check form-check-inline pl-1">
                          <input formControlName="idAnswerRadio" class="form-check-input cursor-pointer radio-button"
                            type="radio" (click)="manageAnswer(n)">
                        </div>
                        <div class="col-xs-9 col-sm-9 col-md-9 col-lg-9 text-left risposta-wrap">
                          {{answer.text}}
                        </div>
                        <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 text-center">
                          {{answer.value}}
                        </div>
                      </div>
 </form>


  createFormAnswer(questions?: Questions[]) {
                                for (let i = 0; i < domande.length; i++) {
                                // other formcontrols questions
                                     for (let n = 0; n < questions[i].answers.length; n++) {
                                        this.formAnswers = this.formBuilder.group({
                                         idAnswerRadio: []
                                })
                              }
                         }
                      }

上面的代码是为答案创建表单的代码。不幸的是,我无法添加 stackblitz

标签: htmlangular

解决方案


您可以绑定到条件disable属性以更改每个radio按钮。此外,您可以收听“主”单选按钮上的更改,以便在其值更改时做出反应。

例子:

打字稿文件:

private isAnswerRadio: boolean = false;

public formAnswers: FormGroup = new FormGroup({
  'isAnswerRadio': new FormControl(...),
  // Other form controls (Initially disabled)
  '...': new FormControl(...),
  ...
});

ngOnInit() {
  this.formAnswers.get('isAnswerRadio').valueChanges.subscribe(newData => {
      if(newData === ...) { // If equals to the desired selection of the radio button
        this.isAnswersRadio = true;
      }
  });
}

getDisabled(): boolean {
  return this.isAnswerRadio;
}

HTML 文件:

<input
    formControlName="idAnswerRadio"
    class="form-check-input cursor-pointer radio-button"
    type="radio"
    (click)="manageAnswer(n)">

<!-- Other inputs... -->

<input [disabled]="getDisabled()">

推荐阅读