Angular 2表单验证,hasError不是函数

时间:2016-02-29 10:00:42

标签: forms validation typescript angular

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

这是我使用过的一段代码:

DepartmentComponent

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'];  
    }

DepartmentComponent模板

   <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文件中(你可以看到)我真的不知道我错在哪里。我做了教程中描述的所有内容,但无法弄清楚为什么会发生这种情况。谢谢你的建议!

4 个答案:

答案 0 :(得分:6)

你应该使用*ngIf="myForm.controls['departmentLocation'].hasError('required')"

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

答案 1 :(得分:3)

代替hasError,您应该使用errors

即应该

myForm.controls['departmentLocation'].errors['required']

即* ngIf

*ngIf="myForm.controls['departmentLocation'].errors['required']"

答案 2 :(得分:0)

这类似于我在此处提供的另一个答案:Form Builder with hasError() for validation throws an error of ERROR TypeError: Cannot read property 'hasError' of undefined

要点是可以使用TypeScript吸气剂以干净的方式解决此问题。

在您的组件类中:

get departmentLocation() { 
    return this.myForm.get( 'departmentLocation' );
}

在您的组件模板中:

<input type="text" formControlName="departmentLocation">
<p class="ui error message" *ngIf="departmentLocation.hasError('required')">Department location is required</p>

注意在Angular 6+中将ngModel与Reactive Forms一起使用已被取消,因此已从上面的示例中删除。

答案 3 :(得分:0)

我在使用时遇到编译错误

loginForm.get('email').hasError('required')

解决了这个问题

loginForm.get('email')?.hasError('required')

像这样使用

<mat-error *ngIf="!loginForm.get('password')?.hasError('required')
          && loginForm.get('password')?.hasError('whitespace')">