bal*_*teo 5 angular2-forms angular
我的 Angular 2 应用程序使用反应形式。
\n\nFormGroup我在我的组件之一中初始化以下内容:
ngOnInit() {\n ...\n\n this.addressForm = this.formBuilder.group({\n address: this.formBuilder.control({\n placeId: this.address.placeId,\n description: this.address.description\n }, addressValidator)\n });\n }\nRun Code Online (Sandbox Code Playgroud)\n\n这是 的定义addressValidator:
import {AbstractControl} from \'@angular/forms\';\n\nexport function addressValidator(control: AbstractControl) {\n\n const {placeId} = control.value;\n\n return (placeId !== undefined && placeId !== null && placeId !== \'\') ? null : {addressValidator: {emptyPlaceId: true}};\n}\nRun Code Online (Sandbox Code Playgroud)\n\n以下是我尝试检查表单控件 ie 是否address有错误的方法:
addressFormErrors(error: string) {\n return this.addressForm.hasError(error, [\'address\', \'addressValidator\']);\n }\nRun Code Online (Sandbox Code Playgroud)\n\n这是调用 addressFormErrors 方法的模板:
\n\n<form [formGroup]="addressForm" (ngSubmit)="updateAddress()" novalidate>\n <div class="form-group" [ngClass]="getFeedbackClasses(addressForm, \'address\', submitted)">\n <div class="input-group">\n <input type="text"\n formControlName="address"\n placeholder="{{\'ADDRESS_FORM.NEW_ADDRESS\' |\xc2\xa0translate}}"\n [ngbTypeahead]="chooseAddress"\n [inputFormatter]="addressFormatter"\n [resultFormatter]="addressFormatter"\n autocomplete="off"\n class="form-control"\n [ngClass]="formControlStatusClass(addressForm, \'address\', submitted)">\n </div>\n <div [hidden]="addressForm.valid || !submitted">\n <div *ngIf="addressFormErrors(\'emptyPlaceId\')" class="form-control-feedback form-control-label">{{\'ADDRESS_FORM.ADDRESS_REQUIRED\' | translate}}</div>\n </div>\n </div>\n ...\n</form>\nRun Code Online (Sandbox Code Playgroud)\n\n这是表单提交时调用的方法:
\n\n updateAddress() {\n this.submitted = true;\n if (this.addressForm.valid) {\n const placeId = this.addressForm.controls[\'address\'].value[\'placeId\'];\n this.userAccountService.updateAddress(placeId)\n .subscribe(() => this.router.navigate([\'/dashboard/useraccount\']));\n }\n }\nRun Code Online (Sandbox Code Playgroud)\n\n编辑:Gunter 是对的:验证器确实在值更改时返回错误对象。问题出在其他地方:它在addressFormErrors方法中没有返回 true - 可能是由于属性路径规范中的一些错误。
有人可以帮忙吗?
\n更改返回的错误对象
{addressValidator: {emptyPlaceId: true}}
Run Code Online (Sandbox Code Playgroud)
到:
{emptyPlaceId: true}
Run Code Online (Sandbox Code Playgroud)
和addressFormErrors来自
addressFormErrors(error: string) {
return this.addressForm.hasError(error, ['address', 'addressValidator']);
}
Run Code Online (Sandbox Code Playgroud)
到:
addressFormErrors(error: string) {
return this.addressForm.controls['address'].hasError(error);
}
Run Code Online (Sandbox Code Playgroud)
修复。
但是,请注意,这并不是一个完全令人满意的解决方案,因为我无法再在同一验证器上指定不同的错误类型。
如果有人能够解释如何在自定义验证器中正确使用 hasError 方法,我将不胜感激。
| 归档时间: |
|
| 查看次数: |
13409 次 |
| 最近记录: |