简体   繁体   English

Angular2反应形式:验证* ngIf中的字段

[英]Angular2 Reactive Form : Validate fields inside *ngIf

I have a form with md-select and md-radio-button fields. 我有一个带有md-selectmd-radio-button字段的表单。 The options under radio button will be displayed according to the option selected in md-select. 单选按钮下的选项将根据md-select中选择的选项显示。 Please visit the plunker . 请参观矮人

You can see I have created the form with the sub-organism radio-button field to be required. 您可以看到我创建了带有需要填写的亚有机单选按钮字段的表单。 It works on the first load. 它在第一次加载时起作用。 But if we select any sub radio button option and then change the organism select box, the form is still valid, without having a valid sub-orgranism value. 但是,如果我们选择任何子单选按钮选项,然后更改生物选择框,则该表格仍然有效,而没有有效的子有机体值。 I need the form to be invalid, if the sub radio button is not checked. 如果未选中子单选按钮,则我需要该表格无效。 Please help. 请帮忙。

Question 2 : Also in the plunk, please uncomment the following lines after line 47 in app.component.ts so that there will be a default value for the fields. 问题2:同样在插件中,请取消对app.component.ts中第47行之后的以下行的注释,以便这些字段具有默认值。 The sub organism radio buttons will be displayed, but the selectbox will be blank. 将显示亚有机体单选按钮,但选择框将为空白。 There is the selected value and thats the reason why sub organism fields are displayed. 存在选定的值,这就是显示亚生物字段的原因。 Not sure why the option is not selected for organisms md-select. 不确定为什么不为有机体md-select选择该选项。

Add a change event to md-select so that if the selection changes, and the form was validated, you can reset the value of selected.sub_organism_id to null . change事件添加到md-select以便如果选择更改并且表单已通过验证,则可以将selected.sub_organism_id的值重置为null That will make the form invalid. 这将使表格无效。

Code snippets: 代码段:

html: 的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: ts:

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

Edited Plunk 编辑的朋克

Update: 更新:

Like @WillHowell said in his comment, "md-select compares values by object reference not object value" which is true. 就像@WillHowell在他的评论中所说,“ md-select通过对象引用而不是对象值比较值”,这是正确的。 I modified your data to an array-object relation, and md-select default value worked here . 我将数据修改为数组对象关系,并且md-select默认值在这里起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM