首页 > 解决方案 > 如何在单选按钮组的更改事件中更改作为模板驱动表单一部分的选定单选按钮?

问题描述

我正在使用 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';
       }
    }
}

标签: angulartypescripteventsangular-materialradio-button

解决方案


通常有两种方法可以实现您的目的。如您所说,使用反应式表单模板驱动的表单。

要更改模板驱动中的值,您必须在组件中使用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' } );
     }
  }
}

希望这是一个足够的解释,它会有所帮助!;)


推荐阅读