Angular复用含表单组件时mat-radio-group选中冲突问题求助
问题描述
我在项目中两次复用了一个包含表单的Angular组件,但选择其中一个组件内的mat-radio-button时,另一个组件内的对应选项会被取消选中,该问题仅出现在mat-radio-group控件上。
我期望两个组件完全独立,选中状态互不影响,但实际无法同时选中两个组件内的mat-radio-group选项,实际效果如下:
组件代码
myform-form.component.html
<form #form="ngForm"> <div style="display: flex; flex-direction: column;"> <mat-radio-group name="test" [(ngModel)]="variable"> <mat-radio-button [value]="false">False</mat-radio-button> <mat-radio-button [value]="true">True</mat-radio-button> </mat-radio-group> <span>Selected: {{variable}}</span> </div> </form>
myform-form.component.ts
import {Component} from "@angular/core"; @Component({ selector: 'myform-form', templateUrl: './myform-form.component.html' }) export class FormComponent { variable: boolean = true; }
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <myform-form></myform-form> <myform-form></myform-form> `, styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'radiatest'; }
解决方案
问题根源是Angular模板驱动表单中,mat-radio-group的name属性是全局表单环境中的唯一标识。复用组件时两个单选组用了相同的name="test",浏览器会将它们判定为同一组单选按钮,导致选中状态互相干扰。
有两种解决方法:
方法一:给每个组件实例生成唯一的
name值
修改组件类,添加一个自动生成或通过@Input传入的唯一标识:// myform-form.component.ts import {Component, Input} from "@angular/core"; @Component({ selector: 'myform-form', templateUrl: './myform-form.component.html' }) export class FormComponent { variable: boolean = true; @Input() groupName: string = `test-${Math.random().toString(36).substring(2, 10)}`; }模板中绑定这个唯一名称:
<!-- myform-form.component.html --> <mat-radio-group [name]="groupName" [(ngModel)]="variable"> <!-- 单选按钮内容保持不变 --> </mat-radio-group>方法二:使用
ngModelOptions让单选组脱离全局表单控制
给mat-radio-group添加[ngModelOptions]="{standalone: true}",使其不再与全局表单内同名称的控件关联:<!-- myform-form.component.html --> <mat-radio-group name="test" [(ngModel)]="variable" [ngModelOptions]="{standalone: true}"> <!-- 单选按钮内容保持不变 --> </mat-radio-group>
两种方法都能让两个组件的单选组完全独立,选中状态不再互相影响。
内容的提问来源于stack exchange,提问作者RedHeadEmile
相关产品推荐
相关产品推荐

