Reputation: 853
I would like to if it is possible to make radio group readonly in Angular.
Upvotes: 1
Views: 6310
Reputation: 1
you can use the HTML "inert" attribute on the radio buttons parent tag. So:
Angular material:
<mat-radio-group formControlName="theme" inert>
<mat-radio-button [value]="A">A</mat-radio-button>
<mat-radio-button [value]="B">B</mat-radio-button>
<mat-radio-button [value]="C">C</mat-radio-button>
<mat-radio-button [value]="D">D</mat-radio-button>
</mat-radio-group>
HTML:
<div inert>
<input type="radio" name="contact" value="A" />
<input type="radio" name="contact" value="B" />
<input type="radio" name="contact" value="C" />
<input type="radio" name="contact" value="C" />
</div>
Upvotes: 0
Reputation: 455
Using a template-driven form, the read-only effect can be achieved very easily. Here's a tutorial. It won't use disabled
on a field, but it will put fields inside *ngIf
s, which - like disabled
- removes the field from the formGroup
's value
.
<form ngForm>
<mat-radio-group [(ngModel)]="viewModel.type" name=type [disabled]="radioDisabled">
<!-- ... -->
</mat-radio-group>
<!-- ... -->
</form>
@Component({ /*...*/ })
export class Component {
radioDisabled = true;
viewModel = {
type: null,
size: "Small",
}
}
In this component, the viewModel
's value will never be affected by the disabled
attribute, which behaviourally is the same as a readonly
attribute in an input. It will just block edition without affecting your main view model object. It still will affect the form.value
, though.
Upvotes: 0
Reputation: 1331
in your style file (.css
or .scss
) file add the following style to the mat-radio-button
tag as follow:
.radio-btn { pointer-events: none; }
Then assign this staying class to the mat-radio-button
tag in your .HTML
file as follows:
<input type="radio" name="example_6" value="4" class="radio-btn">
Upvotes: 0
Reputation: 1
disable will lose the value of the radio, so that's not what we want.
There is no elegant method to make it readonly. Just recover the change with the old value programmatically, like this.
oldValue = getInitialOldValueFromServerOrWhatEver();
onChange(event: MatRadioChange, oldValue: someType) {
if (someCondition) {
this.yourForm.get('yourRadioGroupFormControlName').patchValue(event.value);
} else {
this.yourForm.get('yourRadioGroupFormControlName').patchValue(oldValue);
// provide some info
alert('This can not be changed');
}
}
<mat-radio-group formControlName="yourRadioGroupFormControlName" (change)="onChange($event, oldValue)">
Upvotes: 0
Reputation: 346
The Radio button not allowed to used "Readonly" attributed. Instead you can used "Disabled" attributed for Disabled or Readonly.
HTML :
<input type="radio" name="example_6" value="4" disabled="true">
or you can used Angular Way with Form Group to disable
this.myForm.get('Example').disable();
Upvotes: 1