首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将默认单选按钮设置为选中,并在反应式表单中知道选中了单选按钮组中的哪个单选按钮?

如何将默认单选按钮设置为选中,并在反应式表单中知道选中了单选按钮组中的哪个单选按钮?
EN

Stack Overflow用户
提问于 2019-04-30 15:00:36
回答 1查看 333关注 0票数 1

我已经创建了一组单选按钮。我想要设置一个默认的单选按钮'checked‘,并且每当动态单击其他单选按钮时,我如何才能捕获哪个单选按钮,我可以相应地在我的typescript的条件语句中使用。“CHECKED”标记将不起作用

代码语言:javascript
复制
<form [formGroup]="Form">
  <div class="bx--row">
    <fieldset class="bx--fieldset">
      <legend class="bx--label">HEYHELLOWORLD</legend>
      <div class="bx--form-item">
        <div class="bx--radio-button-group ">
          <input id="radio-button-1" class="bx--radio-button" type="radio" formControlName="selectedOption"
            value="0" checked>
          <label for="radio-button-1" class="bx--radio-button__label">
            <span class="bx--radio-button__appearance"></span>
            HEY<br>
          </label>
          <input id="radio-button-2" class="bx--radio-button" type="radio" formControlName="selectedOption"
            value="1" tabindex="0">
          <label for="radio-button-2" class="bx--radio-button__label">
            <span class="bx--radio-button__appearance"></span>
            HELLO<br>
          </label>
          <input id="radio-button-3" class="bx--radio-button" type="radio" formControlName="selectedOption"
            value="2" tabindex="0">
          <label for="radio-button-3" class="bx--radio-button__label">
            <span class="bx--radio-button__appearance"></span>
            WORLD
          </label>
        </div>
      </div>
    </fieldset>
  </div>
</form>

上面是我的带有反应表单TS的HTML部分:

代码语言:javascript
复制
    heyForm() {
      this.Form = this.formBuilder.group({
          selectedOption: ["", Validators.required],
      });
    }

如何在TS文件中获得选中的值,以便在条件语句中使用被单击的单选按钮?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-30 15:14:34

将表单控件初始化为您希望选中为默认值的任何单选按钮的值。不需要在任何单选按钮中添加默认的checked属性

代码语言:javascript
复制
this.form = this._fb.group({
    selectedOption: ["1", Validators.required], // this will make the second radio button checked as default.
});

如果您想要访问被单击的单选按钮,您可以通过:

代码语言:javascript
复制
this.form.get('selectedOption').value

让一个函数在单选按钮上的(change)事件上获取上面的值。

例如:

代码语言:javascript
复制
<input (change)="foo()" id="radio-button-1" class="bx--radio-button" type="radio" formControlName="selectedOption" value="0">
// inside the method foo() check for the currently selected radio button

请看这里的示例:https://stackblitz.com/edit/angular-kw8bhf

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55915494

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档