gpt4 book ai didi

forms - Angular 2 表单验证,hasError 不是一个函数

转载 作者:搜寻专家 更新时间:2023-10-30 22:04:36 25 4
gpt4 key购买 nike

我尝试对我的输入字段进行验证。

这是我使用的一段代码:

部门组件

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="myForm.controls['departmentLocation'].hasError('required')"

或者任何更好的运气this.departmentName= this.myForm.controls.find('departmentName'); ?

关于forms - Angular 2 表单验证,hasError 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35696611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com