我有一个表单,其中包含一个简单下拉列表的子组件。我需要在表单上要求所有字段,包括子组件的下拉列表。我不清楚实现这一目标的最佳方法。目前,我有以下代码,它没有正确执行用户从子组件下拉列表中选择值的要求。
父组件:
<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>
&#13;
子组件:
<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>
&#13;
答案 0 :(得分:1)
你需要使用ngDefaultControl
和ngModel
,这样就可以注册为表单控件,现在你也不需要对bankAccountId进行双向绑定,你可以只使用一个简单的@Input
,由于ngDefaultControl
添加了双向绑定,因此父级会捕获值更改。
<bank-accounts-dropdown required name="bankAccountId"
[bankAccountId]="disbursementAccount.bankAccountId" ngModel ngDefaultControl>
</bank-accounts-dropdown>