带有hasError()进行验证的表单生成器将引发ERROR TypeError错误:无法读取未定义的属性'hasError' [英] Form Builder with hasError() for validation throws an error of ERROR TypeError: Cannot read property 'hasError' of undefined

本文介绍了带有hasError()进行验证的表单生成器将引发ERROR TypeError错误:无法读取未定义的属性'hasError'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Form Builder在angular 2中实现一个表单

Hi I am implementing a form in angular 2 using Form Builder

在component.ts中,我已经使用formGroup实现了表单

in component.ts i have implemented my form using formGroup

下面是我的代码

public myForm: FormGroup;

constructor(private authenticateservice: AuthenticateService,
              private _fb: FormBuilder
             ) {


}

ngOnInit() {

this.myForm = this._fb.group({
      address: [this.userDetails.address, [<any>Validators.required]],
      address2: ['', [<any>Validators.required]],
      city: ['', [<any>Validators.required]],
      company_address: ['', [<any>Validators.required]],
      company_address2: ['', [<any>Validators.required]],
      company_city: ['', [<any>Validators.required]],
      company_country: ['', [<any>Validators.required]],
      company: ['', [<any>Validators.required , Validators.minLength(3)] ],
      company_tax_number: ['', [<any>Validators.required]],
      company_zip: ['', [<any>Validators.required,  Validators.minLength(5) , Validators.maxLength(7)]],
      country: ['', [<any>Validators.required]],
      email: ['', [<any>Validators.required, Validators.email]],
      first_name: [this.userDetails.first_name, [<any>Validators.required]],
      id: ['', [<any>Validators.required]],
      last_name: ['', [<any>Validators.required]],
      phone: ['', [<any>Validators.required, Validators.minLength(10)]],
      zip: ['', [<any>Validators.required , Validators.minLength(5) , Validators.maxLength(7)]],
      user_type: ['2', [<any>Validators.required]],
      terms: [0, [<any>Validators.required]],
      hash_tag: [''],

    });

}

工作正常。但是当要在前端显示验证时

It is working fine. But when coming to display validations in frontEnd

我这样使用

  <div class="form-group row">
    <div class="col-lg-8">
      <label>Address 2</label>
      <textarea class="form-control" placeholder="Address" rows="2" [readonly]="disabled" id="companyaddress2" formControlName="company_address2"></textarea>
      <span class="help-block form-error text-danger small" *ngIf="myForm.controls['company_address2'].hasError('required')">Company Address 2 is Required.</span>
    </div>
  </div>

它可以正常工作,但是在控制台中抛出错误,如下所示

it is working but throwing the error in console like Below

错误TypeError:无法读取未定义的属性'hasError'

请帮助我进行排序。

谢谢。

推荐答案

您应该这样使用:

<span class="help-block form-error text-danger small" 
  *ngIf="myForm.controls['company_address2'].errors?.required &&
  myForm.controls['company_address2'].touched">Company Address 2 is Required </span>

这篇关于带有hasError()进行验证的表单生成器将引发ERROR TypeError错误:无法读取未定义的属性'hasError'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆