title: How to do onkeypress in angular 4
body: <p>I am trying to implement a input tag that only allows numbers to be put in.</p>
  
  <p>One way that I found work is the following </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input name="num" 
     type="number"
     pattern="[0-9]*" 
     placeholder="Enter new PIN" 
     onkeypress="return event.charCode &gt;= 48 &amp;&amp; event.charCode &lt;= 57"
     title="Numbers only"&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>But I would like to change <code>onkeypress</code> for an angular function. Is there anything that can work similar?</p>
  
  <p>I have tried <code>(keyup)</code>, and <code>(change)</code> but neither work the same. They allow the key to be pressed then remove the number.</p>
  
  <pre><code>&lt;input (keyup)="checkPin($event)" 
    type="number" 
    pattern="[0-9]*" 
    placeholder="Enter new PIN" 
    inputmode="numeric" 
    style="-webkit-text-security: disc;"&gt;&lt;/input&gt;
  </code></pre>
  
  <p>Here is the TS function <code>checkPin</code></p>
  
  <pre><code>checkPin($event: KeyboardEvent) {
    console.log($event)
    let value = (&lt;HTMLInputElement&gt;event.target).value;
  
    if ($event.target) {
      if (value == "") {
        value = value.slice(0, 0);
      }
  
      if (value.length &gt; 4) {
        value = value.slice(0, 4)
      }
      (&lt;HTMLInputElement&gt;event.target).value = value.replace(/\D/g, '');
    }
  }
  </code></pre>