angular – 使用hasError()进行验证的表单生成器抛出错误ERROR TypeError:无法读取未定义的属性’hasError’

前端之家收集整理的这篇文章主要介绍了angular – 使用hasError()进行验证的表单生成器抛出错误ERROR TypeError:无法读取未定义的属性’hasError’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨,我正在使用表单生成器在角度2中实现一个表单

在component.ts中,我使用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: ['',city: ['',company_address: ['',company_address2: ['',company_city: ['',company_country: ['',company: ['',[<any>Validators.required,Validators.minLength(3)] ],company_tax_number: ['',company_zip: ['',Validators.minLength(5),Validators.maxLength(7)]],country: ['',email: ['',Validators.email]],first_name: [this.userDetails.first_name,id: ['',last_name: ['',phone: ['',Validators.minLength(10)]],zip: ['',user_type: ['2',terms: [0,hash_tag: [''],});

}

它工作正常.但是在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>

它正在工作,但在控制台中抛出错误,如下

错误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>

猜你在找的Angularjs相关文章