角反应形式formgroup实例始终未定义

时间:2018-09-12 09:10:12

标签: angular angular-reactive-forms

am创建一个模态作为要在我SPA的相关部分使用的组件。当我单击打开模式的按钮时,我在表单组创建行上收到异常;

export class GerekceModalComponent implements OnInit {
  gerekceForm: FormGroup;
  ngOnInit(): void {
---->    this.gerekceForm = this.formBuilder.group({
      gerekce: ''
    });
  }
  constructor(public activeModal: NgbActiveModal, private formBuilder: FormBuilder) {
   closeModal() {
    this.activeModal.close('Modal Closed');
  }
}

this.gerekceForm始终未定义

  

TypeError:无法读取未定义的属性“有效”

html组件如下所示

<div class="modal-header">
  <h4 class="modal-title">Gerekçe</h4>
  <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
  </button>
</div>
<form [formGroup]="gerekceForm" (ngSubmit)="submitForm()">
  <div class="modal-boy">
    <div class="container">
      <div class="form-group shadow-textarea">
        <label for="exampleFormControlTextarea6">Gerekçe içeriği</label>
        <textarea class="form-control z-depth-1" id="exampleFormControlTextarea6" rows="3" placeholder="gerekçenizi yazınız"></textarea>
      </div>

    </div>
  </div>
  <div class="modal-footer">
    <button class="btn btn-success" [disabled]="!myForm.valid">
      Submit Form
    </button>
  </div>
</form>

此组件根据本教程https://itnext.io/creating-forms-inside-modals-with-ng-bootstrap-221e4f1f5648

构建 我错过了一些东西。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

问题在这里:

    this.gerekceForm = this.formBuilder.group({
            gerekce: ''
    });

代替

   gerekce: ''

尝试

   gerekce: ['']

   gerekce: new FormControl('')

来源: https://angular.io/guide/reactive-forms#step-3-generating-form-controls

答案 1 :(得分:1)

请在TS文件中添加以下代码

export class GerekceModalComponent implements OnInit {
  gerekceForm: FormGroup;
  ngOnInit(): void {
    this.gerekceForm = this.formBuilder.group({
      gerekce: ['']
    });
  }
  constructor(public activeModal: NgbActiveModal, private formBuilder: FormBuilder) {
   closeModal() {
    this.activeModal.close('Modal Closed');
  }
}

请在HTML文件中添加以下代码(您错过了textarea中的formControlName)

<div class="modal-header">
  <h4 class="modal-title">Gerekçe</h4>
  <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
  </button>
</div>
<form [formGroup]="gerekceForm" (ngSubmit)="submitForm()">
  <div class="modal-boy">
    <div class="container">
      <div class="form-group shadow-textarea">
        <label for="exampleFormControlTextarea6">Gerekçe içeriği</label>
        <textarea class="form-control z-depth-1" id="exampleFormControlTextarea6" rows="3" placeholder="gerekçenizi yazınız" formControlName="gerekce"></textarea>
      </div>

    </div>
  </div>
  <div class="modal-footer">
    <button class="btn btn-success" [disabled]="!myForm.valid">
      Submit Form
    </button>
  </div>
</form>