4

how can I select text in input field in TypeScript.

in Javascript this wpuld look like this:

document.getElementById('id').select();

but TypeScript does not support select (error: [ts] Property 'select' does not exist on type 'HTMLElement'.)

Added a few think: It may be a problem beacouse I use dx controls and they create a wraper. You can see here in html:

<dx-text-box _ngcontent-c1="" id="test" ng-reflect-disabled="false" ng-reflect-value="0:00" class="dx-texteditor dx-widget dx-textbox">
<div class="dx-texteditor-container">
<input autocomplete="off" class="dx-texteditor-input" type="text" spellcheck="false" tabindex="0" role="textbox">
<div data-dx_placeholder="" class="dx-placeholder dx-state-invisible"></div><div class="dx-texteditor-buttons-container">
</div></div></dx-text-box>
Jan
  • 167
  • 2
  • 5
  • 16
  • I found a solution (document.getElementById('id').getElementsByTagName('input')[0] as HTMLInputElement).select(); – Jan Nov 16 '17 at 11:10

2 Answers2

10

document.getElementById(string) returns an HTMLElement which does not define a select() method. HTMLInputElement DOES define a select() method and also extends HTMLElement, so if you cast as HTMLInputElement, it should work:

 (document.getElementById('id') as HTMLInputElement).select();
Brian Ball
  • 12,268
  • 3
  • 40
  • 51
2

You can cast the result of document.getElementById() to a more specific type, in this case HTMLInputElement:

(<HTMLInputElement>document.getElementById('id')).select();
// or (TSX-friendly)
(document.getElementById('id') as HTMLInputElement).select();

This is allowed, since HTMLInputElement extends HTMLElement, adding the properties such as select that don't exist on all types of HTML element.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141