角度-未选中默认单选按钮值

时间:2019-03-28 11:59:25

标签: angular binding radio-button angular6 angular-forms

我全部。 我不是Angular专家,但遇到了无法解决的问题! :(

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

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

这是值TAB1的常量

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

这是REST Api响应,其值为TAB2

 {
    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>

我有2种问题:

  1. 当我打开模态时,即使正确读取了“ checkedFirst”的值,在TAB1中也未选中单选按钮“绿色”。如果我继续前进TAB2,然后又回到TAB1,则单选按钮“绿色”被正确选中。此问题仅通过TAB1验证,因为自第一次以来,在TAB2中正确检查了右收音机(“蓝色”收音机)。 它可以取决于const吗?
  2. 即使选中了单选按钮(至少以图形方式),也不会将其视为选中状态,因为对提交表单事件的验证控制失败。此问题在两个选项卡上均得到验证。

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

1 个答案:

答案 0 :(得分:0)

我可以通过在打字稿文件中设置控制值来做到这一点,但是为此,我需要避免使用模板中的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

相关问题