【问题标题】:Check to see if radio buttons are dirty/touched in a reactive form检查单选按钮是否以反应形式变脏/触摸
【发布时间】:2019-11-12 13:33:09
【问题描述】:

My StackBlitz example

我已经构建了一个 Angular 响应式表单。在它上面我有 2 个单选按钮,默认选择一个(但是在我的示例中,它没有在 UI 上显示为选中状态)。

如果单选按钮已更改或触摸,我有一个 ngIf div 应该显示 ||脏,例如

<div formGroupName="radioButtons" class="form-group col-6 pl-0 pt-3">
    <div class="form-check-inline">
        <label for="yes" class="col-12 customradio"
            ><span>yes</span>
            <input value="yes" id="yes" type="radio" name="radiot" formControlName="radiot"/>
        </label>
        <label for="no" class="customradio"
            ><span>no</span>
            <input value="no" id="no" type="radio" name="radiot" formControlName="radiot" />
        </label>
    </div>
    <div class="form-check__related" *ngIf="radioButtons.radiot.touched">
      DISPLAY ME
    </div>

但是,我无法让它工作并得到 ​​p>

Error: Cannot read property 'radiot' of undefined

【问题讨论】:

  • 看来您没有使用 Angular Reactive Forms。使用来自“@angular/forms”的 { FormControl };
  • 控件名称前缺少控件:radioButtons.controls?.radiot.touched
  • @Z.Bolbol 是的,已经尝试过了。控件然后变得未定义

标签: javascript angular typescript angular-reactive-forms


【解决方案1】:

凸出替换

*ngIf="radioButtons.radiot.touched"

*ngIf="form.controls.radioButtons.touched"

你的问题会解决的

https://stackblitz.com/edit/angular-pfctfu

【讨论】:

  • 谢谢!如果我回到原来的默认值,我该如何再次隐藏 div?在这种情况下重新选择是使其不再“脏”。
【解决方案2】:

只需在你的 ts 中添加一个 getter 方法,它会返回表单组:

 get radioButtons(){
    return this.form.get('radioButtons') ;
  }

在你的 html 中

{{radioButtons.controls.radiot.touched}}

【讨论】:

    猜你喜欢
    • 2016-07-29
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 2016-07-28
    • 1970-01-01
    相关资源
    最近更新 更多