简体   繁体   English

Angular2子组件验证

[英]Angular2 Child Component Validation

I have a form that includes a child component for a simple dropdown list. 我有一个包含用于简单下拉列表的子组件的表单。 I need to require all fields on the form including the dropdown list from the child component. 我需要表单上的所有字段,包括子组件的下拉列表。 I am unclear on the best approach to make this happen. 我不清楚实现此目标的最佳方法。 Currently, I have the following code which does not properly enforce the requirement for the user to select a value from the child component dropdown list. 当前,我有以下代码无法正确执行用户从子组件下拉列表中选择值的要求。

Parent Component: 父组件:

 <form (ngSubmit)="createDisbursementAccount()" #createDisbursementAccountForm="ngForm" class="form-horizontal"> <div class="form-group"> <label class="col-xs-4 control-label">{{ "LABELS.DISBURSEMENT_ACCOUNT_DESCRIPTION" | translate }}</label> <div class="col-xs-8"> <input class="form-control" required maxlength="500" type="text" name="description" [(ngModel)]="disbursementAccount.description" /> </div> </div> <div class="form-group"> <label class="col-xs-4 control-label">{{ "LABELS.DISBURSEMENT_ACCOUNT_BANK_ACCOUNT_NAME" | translate }}</label> <div class="col-xs-8"> <bank-accounts-dropdown required [(bankAccountId)]="disbursementAccount.bankAccountId" (bankAccountChanged)="bankAccountChanged($event)"></bank-accounts-dropdown> </div> </div> <span class="pull-right"> <button type="submit" class="btn btn-primary btn-xs" [disabled]="!createDisbursementAccountForm.form.valid">{{ "GLOBAL.SAVE_TEXT" | translate }}</button> <button type="button" class="btn btn-xs" (click)="exitDisbursementAccount()">{{ "GLOBAL.CANCEL_TEXT" | translate }}</button> </span> </form> 

Child Component: 子组件:

 <select [(ngModel)]="selectedBankAccountId" (change)="onChange($event.target.value)" [(disabled)]="isDisabled"> <option value="" disabled>{{ "GLOBAL.DEFAULT_SELECTION" | translate }}</option> <option *ngFor="let bankAccount of bankAccounts" value={{bankAccount.id}}> {{bankAccount.name}} </option> </select> 

You need to use ngDefaultControl and ngModel , this way this is registered as a form control, and now you also do not need the two-way binding for bankAccountId, you can just use a simple @Input , the value change will be caught by the parent since ngDefaultControl adds two-way binding. 您需要使用ngDefaultControlngModel ,通过这种方式将其注册为表单控件,现在您也不需要bankAccountId的双向绑定,您只需使用简单的@Input ,值更改就会被,因为ngDefaultControl添加了双向绑定。

<bank-accounts-dropdown required name="bankAccountId"
    [bankAccountId]="disbursementAccount.bankAccountId" ngModel ngDefaultControl>
</bank-accounts-dropdown>

Demo 演示版

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

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