处理反应形式的嵌套形式组的Angular2 - 4错误

处理反应形式的嵌套形式组的Angular2 - 4错误

问题描述:

伙计们我需要一些关于Angular 4反应形式的帮助。除了验证外,嵌套的表单组也可以正常工作。但是当我尝试在我的html标记中添加一些处理验证时,我的应用崩溃了。处理反应形式的嵌套形式组的Angular2 - 4错误

我的组件的代码如下所示:

createForm() { 
    let options: any = {}; 

    for (let option of this.annoucementOptions) { 
     options[option.title] = new FormControl(false); 
    } 

    let optionsFormGroup: FormGroup = new FormGroup(options); 

    this.annoucementForm = this.fb.group({ 
     address: this.fb.group({ 
      country: ['', [Validators.maxLength(50)]], 
      state: ['', [Validators.maxLength(50)]], 
      city: ['', [Validators.required, Validators.maxLength(50)]], 
      street: ['', [Validators.required, Validators.maxLength(50)]], 
      apartment: ['', [Validators.required, Validators.maxLength(50)]], 
     }), 
     description: this.fb.group({ 
      title: ['', [Validators.required, Validators.maxLength(80)]], 
      shortDescription: [''], 
      livingPlaces: [''], 
      room: [''], 
      options: optionsFormGroup 
     }), 
     priceBlock: this.fb.group({ 
      price: ['', [Validators.required, Validators.maxLength(80)]], 
      type: ['', [Validators.required, Validators.maxLength(80)]], 
     }), 
    }); 
} 

,这是一段我的模板代码:

<form class="form form-lg form-def" *ngIf="annoucementForm" (ngSubmit)="saveDetails(annoucementForm)" name="annoucementForm" [formGroup]="annoucementForm"> 
<div class="form-block" formGroupName="address"> 
    <h2 class="form-block-heading flag-label primary">Address</h2> 

    <ul class="row form-list"> 
     <li class="col-md-6 col-lg-4 form-list-item"> 
      <md-input-container class="d-block"> 
       <input type="text" mdInput placeholder="*Country" formControlName="country"> 
      </md-input-container> 

      <div class="form-error text-danger" 
        *ngIf="annoucementForm.get('country').touched " 
      > 
       <p *ngIf="annoucementForm.get('country').hasError('maxlength')"> 
        *This field be more than 35 characters long. 
       </p> 
      </div> 
     </li> 
    </ul> 

+0

什么错误? – yurzui

+0

错误类型错误:无法在Object.eval [as updateDirectives](ng:///AnnouncementEditorModule/AnnouncementEditor.ngfactory.js:4293:55)读取null' '属性'touch' Object.debugUpdateDirectives [as updateDirectives](eval (在http:// localhost:8081/vendor.js:13:1处)的(http:// localhost:8081/vendor.js:13:1),:12867:21) ,:12279:14) at callViewAction(eval在(http:// localhost:8081/vendor.js:13:1),:12594:17) –

+0

据我所知,Angular不能找到我的形式控制。但我不知道如何正确使用嵌套的表单组。 –

使用

annoucementForm.get('address.country') 

annoucementForm.get(['address', 'country']) 

代替

annoucementForm.get('country') 
+0

非常感谢!!!! –

+0

不客气! – yurzui

+0

不错................. !!! – Juan