str.replace()不存在于' HTMLElement'打字稿

时间:2018-03-22 23:16:18

标签: angular typescript

在我的角度应用程序中,在初始化我想检查是否有任何关键字,如果有替换它我存储的数据..但是当我做

const innerHtml = <HTMLElement>document.querySelector('.inner-html');
innerHtml.replace(...);

我收到此错误[ts] Property 'replace' does not exist on type 'HTMLElement'

如何在打字稿中使用str.replace()?

我环顾四周,无法找到任何对.replace()和此错误的引用

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:3)

.querySelector会返回HTML element,为了获取其内部HTML,您必须访问其.innerHTML属性,然后您需要将其重新分配给the introduction guide 1}}:

innerHTML

请注意,这不是您更新Angular中元素的方式。 Angular与组件一起工作,您将属性绑定到组件,而不是强制选择和更新文本(Angular为您做了那部分)。考虑阅读Here is a short codepen

答案 1 :(得分:1)

The error you are getting has nothing to do with Typescript. You are using document.querySelector() to capture an element in the DOM. That, in turn, returns a HTMLElement object. That object is not a String.

If you want the atual innerHTML of the element, you should use:

const innerHtml = <HTMLElement>document.querySelector('.inner-html').innerHTML;

That should give you a string with the contents of the element. A String has the replace() method.

答案 2 :(得分:0)

Query selector returns a Node. And you need access Node.innerHml

const innerHtml = <HTMLElement>document.querySelector('.inner-html');
innerHtml.innerHmtl.replace(...);