【问题标题】:How will i set default radio button checked and know which radio button is checked from the radio-group in a reactive-form?我将如何设置默认单选按钮检查并知道从反应形式的单选组中检查了哪个单选按钮?
【发布时间】:2019-09-18 19:03:47
【问题描述】:

我创建了一组单选按钮。我想设置一个默认单选按钮“已选中”,并且每当动态单击其他单选按钮时,我如何捕获哪个单选按钮。所以,我可以在我的打字稿的条件语句中相应地使用它。“CHECKED”标签将不起作用

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

上面是我的反应形式的 HTML 部分 TS:

    heyForm() {
      this.Form = this.formBuilder.group({
          selectedOption: ["", Validators.required],
      });
    }

如何获取 TS 文件中选择的值,以便我可以使用在条件语句中单击了哪个单选按钮?

【问题讨论】:

    标签: angular radio-button radio-group reactive-forms


    【解决方案1】:

    使用您希望默认选中的任何单选按钮的值来初始化表单控件。无需在任何单选按钮中添加默认的checked 属性

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

    如果你想访问哪个单选按钮被点击,你可以通过:

    this.form.get('selectedOption').value
    

    (change) 事件中通过单选按钮获取上述值。

    例如:

    <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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-17
      • 2012-04-17
      • 2021-11-10
      • 2023-03-15
      • 2016-07-29
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      相关资源
      最近更新 更多