我感觉很亲密,但不再那么肯定了。也许完全做错了。基本上,用户注册发生在应用程序的三个区域。因此,我决定为用户创建一个单独的组件并进行自己的验证。该组件将向父组件发出true或false,同时在每个表单元素上显示错误消息。
子组件是:
<input type="text" [formControl]="first_name" (input)="onChanges()" class="form-control"/>
<div class="alert" *ngIf="!first_name.valid && first_name.touched">
First name must be at least 3 alaphabets long
</div>
模板:
user_form_is_valid:boolean = false;
//the form
this.rForm = fb.group({
'user': this.fb.group({ first_name: '' }),
'avatar': [null, []],
'client_name': [null, [Validators.required, Validators.pattern('^[a-zA-Z ]+$')]]
});
emittedUserFormValidStatus($event) {
//user-registration componenet emitts if the form is ok or not.
this.user_form_is_valid = false;
if ($event && $event != null) {
this.user_form_is_valid = $event;
}
}
我的父组件:
<app-user-registration (userFormIsValid)="emittedUserFormValidStatus($event)" ></app-user-registration>
<!--Other business related elements/form controls goes here-->
<input type="submit" class="btn btn-primary" value="Register New Client" [disabled]="!rForm.valid || !user_form_is_valid">
模板:
<app-user-registration (userFormIsValid)="emittedUserFormValidStatus($event)" [group]="rForm.controls.user"></app-user-registration>
现在的问题是......验证工作正常。但是当我提交值时,子组件的值不会传递。我当时试过了:
{{1}}
但它无法编译说this.userFormIsValid.emit不是函数。