LoginSignup
1
0

More than 3 years have passed since last update.

[Angular] ERROR in Cannot assign to a reference or variable! を解決する

Last updated at Posted at 2020-02-18

環境

  • Angular CLI: 8.3.25
  • Node: 10.16.3
  • OS: win32 x64
  • Angular: 8.2.14

原因

双方向バインディング(2方向バインディング, Two way binding)の機能を提供していないプロパティに対して双方向バインディングのシンタックス [()] を適用していた

解決策

そもそも双方向バインディングの必要性がなかったため単方向バインディングのシンタックスに修正

状況

ng build --prod を実行したときに発生
ng serve やプロダクションモードでないビルドではエラーが出ないので発見が遅れた

ERROR in Cannot assign to a reference or variable!

そしてこのエラー、情報量少なすぎる!

具体例(私の場合)

修正前

<mat-form-field>
    <mat-label>ラベル</mat-label>
    <mat-select [value]="selected">
        <mat-option [(value)]="role" *ngFor="let role of roles"> {{role}} </mat-option>
    </mat-select>
</mat-form-field>

<mat-option [(value)]="role" *ngFor="let role of roles">role が双方向バインディングされているが、1行上の selected に指定したかった

修正後

<mat-form-field>
    <mat-label>ラベル</mat-label>
    <mat-select [(value)]="selected">
        <mat-option [value]="role" *ngFor="let role of roles"> {{role}} </mat-option>
    </mat-select>
</mat-form-field>

おわりに

このエラーでぱっと検索してみると他の原因で出ている方もいるようなので、あくまで原因の1例って感じですね

「抽象的な良くわからないエラーメッセージ」 → 「検索してもぱっと解決策がない」 のコンボくらうと調査が大変になりますよね

すごい初歩的な間違いだったんですが、ng serve 時にはエラーが出ないこともあって、バグ発見前に開発が進み調査対象が大きくなったので原因のわりに特定が大変でした

いつもエラー解決系の記事にはお世話になっているので書いてみました
みなさんいつもありがとうございます!

1
0
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
1
0