【问题标题】:Radio Buttons in angular2 not working as expectedangular2 中的单选按钮无法按预期工作
【发布时间】:2016-07-18 00:54:27
【问题描述】:

嗨...我有一个表单,里面有单选按钮。其中有两组单选按钮...

1.用于在列表中选择首选手机

2.在列表中选择首选电子邮件

当我在手机中选择单选选项时,它显示为真,但如果我在电子邮件组中选择单选按钮,手机中的选定值将设置为假...我在这里做了一个 plunker 演示 http://plnkr.co/edit/gSosX6kueTxu64CDfjQg?p=preview

myForm: ControlGroup;  
Phones: ControlGroup;
Emails:ControlGroup;
constructor(fb:FormBuilder){
this.Phones=fb.group({
      Phone1:[''],
      Phone2:[''],
      Phone3:['']
});
this.Emails=fb.group({
  Email1:[''],
  Email2:['']
});
this.myForm = fb.group({  
});
}
this.myForm.addControl('Phones', this.Phones));
this.myForm.addControl('Emails', this.Emails);

这就是我访问单选按钮的值并分配给主控制组的方式...有人请帮助我在这种情况下如何正确获取单选按钮的值

【问题讨论】:

    标签: angular


    【解决方案1】:

    一个已知问题是同一 ControlGroup 中的多个单选按钮不起作用https://github.com/angular/angular/issues/7051

    来自 cur3n4 的 comment 显示了一种解决方法

    import {RadioControlRegistry, RadioControlValueAccessor} from 'angular2/src/common/forms/directives/radio_control_value_accessor';
    
    // TODO Monkey patching Radio buttons until https://github.com/angular/angular/issues/7051 is fixed
    export class CustomRadioControlRegistry extends RadioControlRegistry {
    
        select(accessor: RadioControlValueAccessor) {
            (<any>this)._accessors.forEach((c) => {
                if (c[0].control.root === accessor._control.control.root
                  && c[1] !== accessor && c[1]._elementRef.nativeElement.name === (<any>accessor)._elementRef.nativeElement.name) {
                  c[1].fireUncheck();
                }
            });
        }
    }
    

    然后在引导应用程序时,我将 RadioControlRegistry 替换为我的实现: provide(RadioControlRegistry, {useClass: CustomRadioControlRegistry})

    【讨论】:

    • 哦...我不知道这个问题...谢谢@Gunter
    • 我自己还没有尝试过解决方法,但看起来很有希望。
    • 您提到的替代方案非常有效,但我不想在我的应用程序中添加此代码,因为它会导致依赖...我会等到 Angular 解决此问题
    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2019-12-24
    • 1970-01-01
    相关资源
    最近更新 更多