Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Angular CLIでテンプレートのコードがAoTコンパイル通らないケース

Last updated at Posted at 2017-05-09

Angular CLIで ng build ではエラーにならないのに、ng build --aotng build --prod ではエラーになるケースがあります。

エラーとなるのはテンプレート部分のコードで、次のようにstring型の変数の頭に+を付けてnumberに変換していると軒並みエラーになってしまいます。

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div>
      <input type="text" [(ngModel)]="valueA" (ngModelChange)="doCalc()" />
      x
      <input type="text" [(ngModel)]="valueB" (ngModelChange)="doCalc()" />
      = {{resultValue}}
    </div>
    <button (click)="calc(+valueA, +valueB)">NG calc</button>
    <button (click)="resultValue = +valueA * +valueB">NG calc2</button>
    `
})
export class AppComponent {
  valueA: string = '1';
  valueB: string = '2';
  resultValue: number;

  constructor() {
    this.doCalc();
  }

  doCalc() {
    this.calc(+this.valueA, +this.valueB);
  }

  calc(a: number, b: number) {
    this.resultValue = a * b;
  }
}

これを ng build --aot すると +valueA +valueB の部分から以下のエラーが出ます。

Argument of type 'string' is not assignable to parameter of type 'number'.
The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

なんのこっちゃなエラーで混乱しますが、ようするにテンプレート部分にごちゃごちゃしたコードを書かなければいいのです。と解釈して直しましょう...

※環境は @angular/cli 1.0.2, Angular 4.1.1です。以前のバージョンではこのようなコードでもエラーになりませんでしたが、現在はダメみたいです。

Template Syntaxついては【Angular.io】 Template Syntax まとめによくまとまっています。

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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?