LoginSignup
6
3

More than 5 years have passed since last update.

Property 'controls' does not exist on type 'AbstractControl' への対処

Posted at
Property 'controls' does not exist on type 'AbstractControl'

どんな時にこのエラーに出会うか

  • angular4.xを使用している(angular2.xだとどうなるかは知らない)
  • formGroupの中でformArrayを作っているとき
  • htmlファイルで、このformArrayを構成するcontrol要素にアクセスするために下記のようにコーディングした時
<form [formGroup]="sampleForm">
  <div formArrayName="sampleFormArr">
    <div *ngFor="let elem of this.sampleForm.get('sampleFormArr').controls; let i = index" [formGroupName]="i">
      <input formControlName="sampleElementOfArr">
    </div>
  </div>
</form>

  • コンパイルng serveだとこのエラーは出ない。
  • ビルドng buildでこのエラーが出る。つまり開発中にはあまりこのエラーに気づかず、デプロイ時に初めて気づいてハマるリスクがある。

何が問題なのか?

  • この部分this.sampleForm.get('sampleFormArr').controls
  • ここが古い書き方になっている

どのように解決するか

  • tsファイルにcontrolsプロパティを取得するメソッドを用意
  • htmlファイルでget().controlsと書く代わりに、このメソッドをコールする。

  • 具体的にいうと、sample.component.tsに次のような任意の名前のメソッドを用意して、、、

  getSampleArrayControls() {
    return (<FormArray>this.sampleForm.get('sampleFormArr')).controls;
  }
  • html内でこれを呼んでformArrayのcontrolsプロパティを取得する
<div *ngFor="let elem of getSampleArrayControls(); let i = index" [formGroupName]="i">
  <input formControlName="sampleElementOfArr">
</div>

  • このバグ解消のために、半日近く工数を消費してしまった(T T)のでメモ。
6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3