javascript - Angular2 react 形式: Validate fields inside *ngIf

标签 javascript angularjs angular-material2 angular-reactive-forms

我有一个带有 md-selectmd-radio-button 字段的表单。单选按钮下的选项将根据 md-select 中选择的选项显示。请访问plunker

您可以看到我已经创建了带有必填子组织单选按钮字段的表单。它在第一次加载时起作用。但是,如果我们选择任何子单选按钮选项,然后更改有机体选择框,则表单仍然有效,但没有有效的子有机体值。如果未选中子单选按钮,我需要使表单无效。请帮忙。

问题 2:同样在 plunk 中,请取消注释 app.component.ts 中第 47 行之后的以下行,以便字段有默认值。将显示子有机体单选按钮,但选择框将为空白。有选定的值,这就是显示子有机体字段的原因。不确定为什么没有为生物 md-select 选择该选项。

最佳答案

md-select 添加一个 change 事件,以便在选择更改且表单已验证时,您可以重置 selected.sub_organism_id 的值null。这将使表格无效。

代码片段:

html:

<md-select [formControl]="form.controls['organism']" 
           style="width:100%;" 
           [(ngModel)]="selected.organism_id" 
           (change)="resetForm($event)">
  <md-option *ngFor="let organism_id of getIds()" [value]="organism_id">
    {{ organisms[organism_id].name }}
  </md-option>
</md-select>

ts:

resetForm(org){
  if(this.form.valid){
    this.selected.sub_organism_id = null;
  };  
}

Edited Plunk

更新:

就像 @WillHowell 在他的评论中所说,“md-select 通过对象引用而不是对象值来比较值”,这是正确的。我将您的数据修改为数组对象关系,并且 md-select 默认值有效 here

关于javascript - Angular2 react 形式: Validate fields inside *ngIf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45188203/

相关文章:

angular - 如何在单击按钮或悬停时将 Angular Material (2.x +)对话框定位到屏幕的右侧

javascript - window.clipboardData 不是 Javascript 的一部分?

javascript - JS : How to turn this string into date object

html - 尝试在 html 模板中显示 GIF 时引发错误

angularjs - 使用 Selenium 测试 AngularJS

Angular2+ Material 菜单的行为与菜单不同

javascript - 如何将 bootstrap 年历与 mysql 库连接

javascript - 提供 react 后如何在移动设备上隐藏 react 文本

html - 背景图像在 AngularJS 的 IE8 中不起作用

angular - 如何在 Angular 4 中禁用 md-select 的键盘交互?