typescript 如何在打字稿中添加innerhtml?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45712292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:49:13  来源:igfitidea点击:

How to add innerhtml in typescript?

typescript

提问by Nivitha G

I am using typescript in my application.

我在我的应用程序中使用打字稿。

html code:

html代码:

<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?

如何使用打字稿为文本框分配空值?

采纳答案by Nitzan Tomer

Html input elements have the value property, so it should be:

Html 输入元素具有 value 属性,因此它应该是:

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

Notice that I also used HTMLInputElementinstead of HTMLElementwhich does not have the valueproperty.

请注意,我还使用HTMLInputElementHTMLElementwhich 不具有的value属性。

回答by Sandeep Bhaskar

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

您可以使用模型值绑定到元素,而不是使用 id 和内部 html

Html code:

html代码:

<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

如果你想通过 id 使用内部 Html 那么你必须使用这个

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

TypeScript 使用 '<>' 来包围转换 Typescript 代码:

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

回答by Harshit Singhai

You can also use it like this

你也可以这样使用

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

Works in Typescript 2.0

适用于打字稿 2.0