【问题标题】:Angular - list of radio button not workingAngular - 单选按钮列表不起作用
【发布时间】:2017-09-19 01:09:48
【问题描述】:

我在使用表单中的单选按钮列表时遇到问题。在我的代码下方。
查看

<form novalidate (ngSubmit)="onSubmit()" [formGroup]="perito">
    <div class="form-group row">
        <table class="table">
            <thead></thead>
            <tbody>
                <tr *ngFor="let p of periti">
                    <td>{{p.nome}} {{p.cognome}}</td>
                    <td>{{p.indirizzo}} {{p.civico}} - {{p.cap}} 
                        {{p.comune}}
                    </td>
                    <td><input formControlName="idPerito" type="radio" [value]="p.id" (change)="onSelect(p.id)"></td>
                </tr>
            </tbody>
        </table>
    </div>
</form>

控制器

perito: FormGroup;
ngOnInit() {
    this.perito = new FormGroup({
        idPerito: new FormControl()
    });
}
onSelect() {
    console.log(this.perito.value);
}

问题是当我选择一个单选按钮时:

  1. 所有其他单选按钮也被选中
  2. 表单对象未定义

管理单选按钮列表的正确方法是什么?谢谢。

编辑 - 这就是我填充 periti 数组的方式:

this.peritiSrv.getPeriti()
    .then(res => {
        this.periti = res;
     })
     .catch();

无论如何,两个periti 对象不可能有相同的id,因为它们是主键。

【问题讨论】:

  • 你能提供你的 periti 阵列吗?也许在某个地方你有相同的 id。因为如果你的单选按钮的值相同,这可能会发生。
  • 查看我的编辑,谢谢。
  • 我是想举一个这个数组的例子。

标签: forms angular radio-button


【解决方案1】:

您的表单对象是undefined 可能是因为在创建组件时它尚未实例化(constructed)。尝试将 formGroup 创建行从 ngOnInit() 钩子移动到该组件的 constructor 主体,

控制器

perito: FormGroup;
constructor() {
    this.perito = new FormGroup({
        idPerito: new FormControl('')
    }); // empty string passed in as the initial value of the FormControl instead of no argument
}
// no ngOnInit() implementation
onSelect() {
    console.log(this.perito.value);
}

查看问题是否仍然存在。

【讨论】:

  • 问题依然存在。我认为(但我可能是错的)该对象是未定义的,因为由于选择了两个单选按钮,控制器不知道哪个是传递的值。
猜你喜欢
  • 1970-01-01
  • 2017-07-08
  • 2011-05-03
  • 1970-01-01
  • 2011-02-10
  • 2015-12-11
  • 2018-01-17
  • 2015-03-11
  • 1970-01-01
相关资源
最近更新 更多