【发布时间】:2016-06-12 07:38:44
【问题描述】:
我尝试对我的输入字段进行验证。
这是我使用的一段代码:
部门组件
import {
FORM_DIRECTIVES,
FormBuilder,
ControlGroup,
Validators ,
AbstractControl
} from 'angular2/common';
@Component({
selector: 'my-departments',
providers: [HTTP_PROVIDERS, DepartmentService],
directives: [FORM_DIRECTIVES, Alert],
styleUrls: ['app/department.component.css'],
templateUrl: 'app/department.component.html',
pipes:[SearchPipe]
})
export class DepartmentComponent implements OnInit {
myForm: ControlGroup;
departmentName: AbstractControl;
departmentLocation: AbstractControl;
constructor(private _router: Router, private _departmentService: DepartmentService, fb: FormBuilder) {
this.myForm = fb.group({
'departmentName': ['', Validators.required],
'departmentLocation': ['', Validators.required]
});
this.departmentName= this.myForm.controls['departmentName'];
this.departmentLocation= this.myForm.controls['departmentLocation'];
}
部门组件模板
<form [ngFormModel]="myForm"
(ngSubmit)="addDepartment(newItem)" [hidden]="!showAddView" align="center">
<div>
<label for="editAbrv">Department name:</label><br>
<input type="text" [(ngModel)]="newItem.departmentName" [ngFormControl]="myForm.controls['departmentName']" >
<div *ngIf="departmentName.hasError('required')" class="ui error message"><b style="color:red;">Name is required</b></div>
</div>
<div>
<label for="editAbrv">Department Location:</label><br>
<input type="text" [(ngModel)]="newItem.departmentLocation" [ngFormControl]="myForm.controls['departmentLocation']" >
<div *ngIf="departmentLocation.hasError('required')" class="ui error message"><b style="color:red;">Location is required</b></div>
</div>
<div>
<button type="submit" class="ui button">Submit</button>
<button><a href="javascript:void(0);" (click)="showHide($event)" >
Cancel
</a></button>
</div>
</form>
问题是我得到一个错误:.hasError 不是一个函数。 hasError 函数在我的 html 文件中(你可以看到)我真的不知道我错在哪里。我做了教程中描述的所有事情,但无法弄清楚为什么会发生这种情况。感谢您的建议!
【问题讨论】:
-
试试
*ngIf="departmentLocation?.hasError('required')" -
我解决了这个问题:*ngIf="myForm.controls['departmentName'].hasError('required')"。我只是不清楚为什么它会以这种方式工作:/
-
但是这些行
this.departmentName= this.myForm.controls['departmentName'];在构造函数内部?从您的代码中并不完全清楚,因为缺少}。 -
是的,这些在我的构造函数中,因为我认为我可以只使用部门名称,而不是整行:this.myForm.controls['departmentName'];我不认为我错过了}。我只是没有复制整个班级的实现:)
-
那么缩进是错误的(已修复)。这太奇怪了。我不明白为什么这不起作用。
标签: forms validation typescript angular