To achieve your goal, there are generally two approaches: using either Reactive Forms or Template-driven Forms, as you mentioned.
If you want to change the value in a template-driven form, you need to utilize the LocalReference and @ViewChild() decorator in your component. Here's an example:
In HTML:
<mat-radio-group>
<mat-radio-button value="1" #email>Email</mat-radio-button>
<mat-radio-button value="2">Mobile</mat-radio-button>
</mat-radio-group>
<br/>
You can then use the local reference like "#email" in the component code, for instance:
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-reactive',
templateUrl: './reactive-form.component.html'
})
export class TemplateFormComponent implements OnInit {
constructor() {}
@ViewChild('email')
emailRB: MatRadioButton;
RadioChanged( event ) {
let result = confirm('Are you sure you want to reject? You cannot reverse this decision');
if (!result) {
this.emailRB.focus();
}
}
This code snippet can assist in selecting the desired radio button.
For more examples, refer to the link below:
However, the preferable method is utilizing Reactive Forms, such as:
<form class="radio-btn-container" [formGroup]="acceptanceFG">
<label class="radio-main-lable">Acceptance: </label>
<mat-radio-group formControlName="acceptance">
<mat-radio-button value="A">
<span class="radio-option-lable">Accept</span>
</mat-radio-button>
<mat-radio-button value="R">
<span class="radio-option-lable">Reject</span>
</mat-radio-button>
</mat-radio-group>
</form>
And in the component file:
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
@Component({
selector: 'app-reactive',
templateUrl: './reactive-form.component.html'
})
export class ReactiveFormComponent implements OnInit {
acceptanceFG: FormGroup;
constructor(private _formBuilder: FormBuilder ){}
ngOnInit() {
this.acceptanceFG= this._formBuilder.group({
acceptance: new FormControl( null, { validators: Validators.required }),
});
}
RadioChanged( event ) {
let result = confirm('Are you sure you want to reject? You cannot reverse this decision');
if (!result) {
this.acceptanceFG.patchValue( { acceptance: 'R' } );
}
}
}
I hope this explanation was sufficient and beneficial! 😉