'How to add innerhtml in typescript?

I am using typescript in my application.

html code:

<input type="text" name="lastname" id="last">

Typescript code:

let myContainer = <HTMLElement>document.getElementById('last');
myContainer.innerHTML = "";

I want to set the empty value for the last name field using typescript. I am using above code. But cannot able to add empty value using typescript.

I also tried by using below code:

document.getElementById('last').innerHTML = "";

How to assign empty value for the textbox using typescript?



Solution 1:[1]

You can also use it like this

const element: HTMLElement = document.getElementById('personDetails') as HTMLElement
element.innerHTML = 'Hello World'

Works in Typescript 2.0

Solution 2:[2]

You can use model value to bind to the element instead of using the id and inner html

Html code:

<input type="text" name="lastname" id="last" ng-model="innerHtml">

Typescript code:

let innerHtml :string = "";

OR

if you want to use the inner Html by id then you have to use this

TypeScript uses '<>' to surround casts Typescript code:

let element = <HTMLInputElement>document.getElementById("last");
element.value = "Text you want to give";

Solution 3:[3]

this is not a good practice, what we define in this way is not always the correct type.

let myContainer = document.getElementById('last') as HTMLInputElement;
myContainer.value = "";

or

const element: HTMLElement = document.getElementById('personDetails') as HTMLElement
element.innerHTML = 'Hello World'

if it is input use just HTMLInputElement

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Harshit Singhai
Solution 2 Sandeep Bhaskar
Solution 3 Jaxoo Jack