I have reactive form template in html of my class:
<form [formGroup]="formGroup">
<md-radio>
[value]="one"
[formControlName]="radioButton"
</md-radio>
<md-radio>
[value]="two"
[formControlName]="radioButton"
[disabled]="disabled_flag"
</md-radio>
</form>
and into code, I created form group:
this.formGroup = this.fb.group({
radioButton: [
{ value: "two", disabled: false },
[],
[],
{ updateOn: blur },
],
});
If I changed disabled_flag
into code in true, radio button "two" will be disabled, but I got this message in browser;
It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors. Example: form = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true}, Validators.required), last: new FormControl('Drew', Validators.required) });
So I need to dynamically change this flag and how to do that properly and skip this warning message, or how to disable radio button properly?
CodePudding user response:
You can do something like this. This should work.
this.formGroup = this.fb.group({
radioButton: [
{ value: "two", disabled: this.disabled_flag },
[],
[],
{ updateOn: blur },
],
});
CodePudding user response:
Yes, that is a good warning to exist, as it is sometimes "misused" with reactive forms... Disabling the form control won't work, as it will disable all buttons...
How to get rid of the error then? The thing I can think of is using ViewChild
to access the element and disable it that way.
<input type="radio" formControlName="radioButton" value="two" #radio />
And TS code:
@ViewChild('radio') radio: ElementRef;
and when you want to disable it just set it to false:
this.radio.nativeElement.disabled = true