Input box attribute set dynamically on radio button change

ぃ、小莉子 提交于 2019-12-04 19:53:03

Here i have updated the stackblitz you provided and changed a few things to fix your implementation.

They way you were settings required i.e. [required]="(curOptionIndex == question.id) && optsel != 2" curOptionIndex and optsel were updating on each radio button change event. So if it set the first comment box required correctly on a selection in first radio group, when you select an option in the second radio group, optsel andcurOptionIndex update and the required property of first comment box becomes invalid again. I have done the following two changes in you solution:

Change 1:

I have added commentsRequired array for each question indicating on which options the comments are required for each question. Also, changed [required]="(curOptionIndex == question.id) && optsel != 2" to [required]="question.commentsRequired.indexOf(question_sel.value)>-1". So e.g. if commentsRequired from first question is ["49","50"] it means that comments are required for options with these IDs in that question.

Change 2:

ExpressionChangedAfterItHasBeenCheckedError was occurring in case of [disabled]="!questionForm.valid" due to which and some *ngIf conditions due to which submit button styles were not updating on radio buttons change. So i ran change detection cycle explicitly:

import { ChangeDetectorRef } from '@angular/core';

constructor(private cdRef:ChangeDetectorRef) {}

ngAfterViewChecked()
{  
  this.cdRef.detectChanges();
}

Now in current solution, if you select third option in first radio group, the comments for that panel will become required. For second radio group, comments will be required for 4th and 5th options. You can change contents of commentsRequired for each section to specify the options for which comments are required.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!