title: Angular 5: Where should type conversion between form field values (strings) and model properties (eg numbers) happen?
body: <p>I'm new to Angular and can't figure out, how to convert types between form field values (always strings) and typed model properties.</p>
  
  <p>The following component should double a number. The result is shown in the console. </p>
  
  <pre><code>import { Component } from '@angular/core';
  
  @Component({
    selector: 'app-model-view-conversion',
    template: `
      &lt;input [(ngModel)]="aNumber" (keyup)="double()" /&gt;
    `
  })
  export class ModelViewConversionComponent {
  
    aNumber: number;
  
    double() {
      console.log(this.aNumber + this.aNumber); // input 7 -&gt; 77
    }
  
  }
  </code></pre>
  
  <p>Neither TypeScript nor Angular magically converts between strings and numbers. So the result is of course a concatenation and not the addition. That's only for simple demonstration purpose.</p>
  
  <p><strong>The question is, where/how should the conversion happen?</strong></p>
  
  <p>I came up with something like the following:</p>
  
  <pre><code>import { Component, DoCheck } from '@angular/core';
  
  @Component({
    selector: 'app-model-view-conversion',
    template: `
      &lt;input [(ngModel)]="viewNumber" (keyup)="double()" /&gt;
    `
  })
  export class ModelViewConversionComponent implements DoCheck {
  
    viewNumber: string;
    modelNumber: number;
  
    ngDoCheck() {
      this.modelNumber = parseInt(this.viewNumber);
    }
  
    double() {
      console.log(this.modelNumber + this.modelNumber); // input 7 -&gt; 14
    }
  
  }
  </code></pre>
  
  <p>This works but does not really help. The model and the view must be kept in sync manually. Their must be something like converters, known from JavaServer Faces for example.</p>
  
  <p>Or what's about getters/setters in the model?</p>
  
  <pre><code>import { Component } from '@angular/core';
  
  @Component({
    selector: 'app-model-view-conversion',
    template: `
      &lt;input [(ngModel)]="aNumber" (keyup)="double()" /&gt;
    `
  })
  export class ModelViewConversionComponent {
  
    num: number;
    set aNumber(numAsString) {
      this.num = parseInt(&lt;any&gt;numAsString);
    };
    get aNumber() {
      return this.num;
    }
  
    double() {
      console.log(this.num + this.num);
    }
  
  }
  </code></pre>
  
  <p>This feels also clumsy and verbose to me. TypeScript (I'm new to TypeScript too) requires the <code>&lt;any&gt;</code> cast to compile nicely.</p>
  
  <p>Could anyone point me in the right direction. Thanks.</p>