【问题标题】:Angular 2 form validation, hasError is not a functionAngular 2 表单验证,hasError 不是函数
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 当我使用 this.departmentName= this.myForm.controls.find('departmentName'); 时它可以工作。真的很奇怪,因为在教程中我发现 this.departmentName= this.myForm.controls.find ['departmentName' ];谢谢:)
【解决方案2】:

你应该使用errors代替hasError

即应该是

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

即使用 *ngIf

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

【讨论】:

  • 使用这种方法,当控件有效时(所以,errors 为空),它会显示下一条消息:Cannot read property 'required' of null
  • 快速技巧可能是检查错误是否为空(用于控制没有错误时的条件),即 *ngIf="myForm.controls['departmentLocation'].errors && myForm.controls[' departmentLocation'].errors['required']"
  • 为防止出现非空错误,将其用作myForm.controls['departmentLocation'].errors?.required
  • 为什么人们不直接使用 .符号它更容易阅读。我得到的重点是 [' --- '] 但现实是它只是一个对象,应该这样对待
  • 顺便说一句,这个答案大部分正确的原因是因为这就是对象中的内容。如果人们可以阅读对象,这个答案会更容易为自己找到
【解决方案3】:

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

要点是可以使用 TypeScript getter 以干净的方式解决这个问题。

在你的组件类中:

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 已被弃用,因此已从上面的示例中删除。

【讨论】:

    【解决方案4】:

    我在使用时遇到编译错误

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

    这解决了它

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

    这样使用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 2016-10-30
      • 2018-05-27
      • 2016-11-28
      • 2016-08-19
      • 2019-03-12
      相关资源
      最近更新 更多