通常有两种方法可以实现您的目的。如您所说,使用 Reactive Forms 或 Template-driven Forms。
要更改模板驱动中的值,您必须在组件中使用 LocalReference 和 @ViewChild() 装饰器,如下例所示:
在 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/>
有一个像“#email”这样的本地引用,在组件中我们可以这样使用它:
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();
}
}
因此,此代码可以帮助选择所需的单选按钮。
更多示例见以下链接:
https://www.concretepage.com/angular-material/angular-material-radio-button
但更好的方法是使用这样的响应式表单:
<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>
关于组件:
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' } );
}
}
}
希望这是一个足够的解释,它会有所帮助! ;)