Angular - 未选中默认单选按钮值

问题描述 投票:0回答:1

我都是。我不是角色专家,而且我遇到了一个我无法解决的问题! :(

这是一个场景:有一个带有2个选项卡的模态,每个选项卡中都有一个带有一组单选按钮的表单。 (组件是相同的)

  1. 在TAB1中,单选按钮的值来自environment.ts文件中定义的const。
  2. 在TAB2中,单选按钮的值来自REST Api响应。我想要的是,如果属性“checkedFirst”为true,则单选按钮被选中为默认值。

这是值TAB1的const

export const ColorsForRadio: Colors[] = [
  {
    id: '1',
    name: 'red',
    checkedFirst: false
  },
  {
    id: '2',
    name: 'green',
    checkedFirst: true
  }
]

这是重置TAB2的REST Api响应

 {
    id: '1',
    name: 'red',
    checkedFirst: false
  },
  {
    id: '3',
    name: 'blue',
    checkedFirst: true
  },
   {
    id: '5',
    name: 'yellow',
    checkedFirst: false
  }

这是HTML

<div *ngFor="let color of colorsForRadio$ | async">
      <label class="radio-label">
        <input type="radio" formControlName="colorsForRadio" class="radio" [value]="color" [checked]="color.checkedFirst"/>
        {{ color.name }}
      </label>
    </div>

我有两种问题:

  1. 当我打开模态时,即使正确读取“checkedFirst”的值,在TAB1中也不会检查单选按钮“绿色”。如果我在TAB2上移动并且在返回到TAB1后,单选按钮“绿色”将被正确选中。此问题仅通过TAB1进行验证,因为在TAB2中,自第一次以来正确检查了正确的无线电(“蓝色”无线电)。它可以依赖于const?
  2. 即使选中单选按钮(至少以图形方式),也不会将其视为已选中,因为提交表单事件的验证控制失败。此问题会在两个选项卡上进行验证。

有人可以给我一些如何解决的建议吗?谢谢

angular binding radio-button angular6 angular-forms
1个回答
0
投票

我会通过在typescript文件中设置控件值来实现,但为此我需要避免模板中的async管道,而是执行订阅.ts并相应地将值设置为formControl。

假设您有一个变量apiData,您可以使用该变量从API获取数据并使用它在模板中循环。

就像是:

ngOnInit() {
  this.parentForm = new FormGroup({
    'color': new FormControl()
  })

  this.getData().subscribe((data) => {  // getData() is request to the API
    // find the data which was true,
    let defaultValue = data.find(eachData => eachData.checkedFirst);
    if (defaultValue) {
      this.parentForm.get('color').setValue(defaultValue.name)
    }
    this.apiData = data;
  })
}

您的HTML将如下:

<form [formGroup]="parentForm">
  <div *ngFor="let eachCheckBox of apiData">
    {{eachCheckBox.name}}
    <input type="radio" formControlName="color" [value]="eachCheckBox.name">
  </div>
</form>

在这里查看一个工作示例:https://stackblitz.com/edit/angular-jlgidp?file=src%2Fapp%2Fapp.component.ts

© www.soinside.com 2019 - 2024. All rights reserved.