【发布时间】:2018-03-28 08:32:35
【问题描述】:
我想将我的 ngForm 和 ngModelGroup 从父组件转移到子组件,并在子组件中使用表单验证功能。
父组件.html:
<md-step [stepControl]="createIntegrationPartnerRequestGroup">
<form #createIntegrationPartnerRequestForm="ngForm">
<div ngModelGroup="createIntegrationPartnerRequestGroup" #createIntegrationPartnerRequestGroup="ngModelGroup">
<div class="row p-row-padding">
<div class="col-xs-12">
<ng-template mdStepLabel>
{{'INTEGRATION_PARTNER_REQUEST' | translate}}
</ng-template>
</div>
</div>
<integration-partner-request [form]="createIntegrationPartnerRequestForm"
[model]="createIntegrationPartnerRequestGroup"></integration-partner-request>
</div>
</form>
</md-step>
子组件.html(摘录):
<div class="row p-row-padding">
<div class="col-xs-6">
<md-input-container class="p-full-width">
<input mdInput
ngModel name="name"
#name="ngModel"
required
(change)="showForm()"
placeholder="{{'WELCOME_WIZARD.PARTNER_NAME' | translate}}">
<md-error *ngIf="name.touched && name.invalid">
<span *ngIf="name.errors.required">
{{'WELCOME_WIZARD.FIELD_REQUIRED' | translate}}
</span>
<span *ngIf="name.errors.pattern">
{{'WELCOME_WIZARD.INVALID_FIELD_FORMAT' | translate}}
</span>
</md-error>
</md-input-container>
</div>
<div class="col-xs-6">
<md-input-container class="p-full-width">
<input mdInput
ngModel name="status"
#status="ngModel"
placeholder="{{'WELCOME_WIZARD.PARTNER_STATUS' | translate}}">
<md-error *ngIf="status.touched && status.invalid">
<span *ngIf="status.errors.required">
{{'WELCOME_WIZARD.FIELD_REQUIRED' | translate}}
</span>
<span *ngIf="status.errors.pattern">
{{'WELCOME_WIZARD.INVALID_FIELD_FORMAT' | translate}}
</span>
</md-error>
</md-input-container>
</div>
</div>
子组件.ts:
export class ChildComponent implements OnInit {
@Input() public form: FormGroup;
@Input() public model: NgModelGroup;
@Input() public type: string;
public formResult;
public modelResult;
constructor() {
}
ngOnInit() {
this.formResult = this.form;
this.modelResult = this.model;
}
public showForm() {
console.log(this.formResult);
console.log(this.modelResult);
}
}
子组件中还有一个按钮,只有在必填字段不为空时才有效,但事实并非如此,因为modelResult 没有任何字段值...:
<button
class="p-full-width"
md-raised-button
[disabled]="formResult.invalid"
mdStepperNext>
{{'WELCOME_WIZARD.NEXT' | translate}}
</button>
我做错了什么?
【问题讨论】:
标签: angular typescript