angular - 如何在单选按钮组的更改事件中更改作为模板驱动表单一部分的选定单选按钮?
问题描述
我正在使用 Angular Material,单选按钮组,在一个组中有两个单选按钮,一个是“接受”,另一个是“拒绝”,具有值“A”和“R”。我弹出一个确认对话框以响应用户单击“拒绝”单选按钮,如果用户在确认中指定“取消”,则需要将选定的单选按钮更改为“接受”(A)。
我的代码在单选按钮组的更改事件中。
单选按钮组使用 [(ngModel)] 绑定到变量“statusCode”,并且是模板驱动表单的一部分。
onRadioChange($event: MatRadioChange) {
if ($event.value === 'R' && this.userNeedsToChange) {
let result = confirm('Are you sure you want to reject? You cannot reverse this decision');
if (!result) {
this.statusCode = 'A';
}
}
}
解决方案
通常有两种方法可以实现您的目的。如您所说,使用反应式表单或模板驱动的表单。
要更改模板驱动中的值,您必须在组件中使用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' } );
}
}
}
希望这是一个足够的解释,它会有所帮助!;)
推荐阅读
- python - Python - 如何将单独的模块(不是函数)作为单独的进程运行?
- sharepoint - Sharepoint Online - 只读用户 - PnP 现代搜索 - 无法获得搜索结果
- linux - 不能移动
至 : 没有权限 - python - 如何欺骗 Thread.start() 在 python 中多次运行
- python - 已解决:在 volatile 设置中向 ORM SQLAlchemy 表添加新列
- javascript - Unexpected SyntaxError:输入意外结束
- reactjs - react-select:当您没有搜索选项时自动建议“其他”选项
- javascript - 为什么我的嵌套等待函数没有等待
- visual-studio-code - (tasks.json)我不知道如何使用 WSL 作为 shell 来使用转义字符
- reactjs - 如何链接到 Shopify 嵌入式应用程序中的另一个页面?