【问题标题】:radio button with same formcontrol name is getting selected together on click in angular7在angular7中单击时,具有相同formcontrol名称的单选按钮被一起选中
【发布时间】:2020-05-23 20:16:34
【问题描述】:

https://stackblitz.com/edit/angular-7aqzj2

places = ['effil tower','new discover']

new FormGroup({place: new FormControl()});
 <div *ngIf="places?.length > 0" class="col-12">
            <div style=" padding-top: 1em; ">
                <label  *ngFor="let place of places">
                    <input  formControlName="place" type="radio">{{place}}
                </label>
            </div>
        </div>

我正在尝试添加具有相同表单控件名称的单选按钮,并且值来自服务。

这样做时,它具有相同的表单控件名称,因此会同时被选中。

有没有办法区分两者并一次选择一个?

【问题讨论】:

  • 抱歉,问题不是很清楚。你能创建一个Minimal, Complete, and Verifiable example吗?也许是堆栈闪电战来说明到底发生了什么。
  • 请查看下面的 stackblitz。 stackblitz.com/edit/angular-7aqzj2
  • 我正在尝试选择一个单选按钮,但它同时被选中
  • 您的 stackblitz 演示中有错误。下拉值未加载。请检查。
  • 抱歉我错过了保存.. 立即尝试

标签: javascript html angular select radio-button


【解决方案1】:

您需要为每个选项使用属性绑定:

<input  formControlName="place" type="radio" [value]="place">

【讨论】:

  • 非常感谢..它起作用了..只是好奇如何在下拉列表中默认设置数组的第一个索引?
  • 很高兴为您提供帮助!抱歉没有得到你。你说的是哪个下拉菜单?
  • 扩展您的 *ngFor 以通过 *ngFor="let place of places; let first = first;" 传递第一个值。然后设置 selected 如果 first 为真,&lt;option [selected]="first"&gt;&lt;/option&gt;
  • 我在屏幕上确实有 2 个下拉菜单。默认情况下,我想显示数组的第一个索引。例如,应该选择法国和巴黎
  • @atitpatel:也许this 可以提供帮助。
【解决方案2】:

输入需要定义一个。此外,当您构造 FormGroup 时,您可以根据需要定义一个默认值。

这个问题可能对你有更多帮助。 Angular 5 Reactive Forms - Radio Button Group

 <div *ngIf="places?.length > 0" class="col-12">
            <div style=" padding-top: 1em; ">
                <label  *ngFor="let place of places">
                    <input  formControlName="place" type="radio" value=place>{{place}}
                </label>
            </div>
        </div>

【讨论】:

    【解决方案3】:

    places = ['effil tower','new discover']
    
    new FormGroup({place: new FormControl(this.places[0])});
     <div *ngIf="places?.length > 0" class="col-12">
                <div style=" padding-top: 1em; ">
                    <label  *ngFor="let place of places">
                        <input  formControlName="place" type="radio" [value]="place">{{place}}
                    </label>
                </div>
            </div>

    希望这会有所帮助。 [value]="place" 和 FormControl(this.places[0])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-09
      • 2015-08-27
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多