1

In my angular app, On init I want to check if there are any keywords and if there are replace them with data I have stored.. but when I do

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

I get this error [ts] Property 'replace' does not exist on type 'HTMLElement'

How can I use str.replace() in typescript??

Ive looked around and I cant find any reference to .replace() and this error

any help would be appreciated!

Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152

3 Answers3

5

.querySelector returns an HTML element, in order to get its inner HTML you'd have to access its .innerHTML property, you would then need to re-assign that to innerHTML:

// this selects an element with CSS class "inner-html"
const element = <HTMLElement>document.querySelector('.inner-html');
element.innerHTML = element.innerHTML.replace(...);

Note that this is not how you would update elements in Angular. Angular works with components and you'd bind a property to a component rather than imperatively select and update the text (Angular does that part for you). Consider reading the introduction guide.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • The reason Im doing it this way is because the content is dynamically loaded from an api, so If it was on my actual page I would just use interpolation – Smokey Dawson Mar 22 '18 at 23:22
  • @A61NN5 you should consider loading the text via Angular's HTTP service - and then `.subscribing` to the HTTP request and assigning a property on your model there - any change to a property would _automatically_ update components bound to it (aka "data binding"). – Benjamin Gruenbaum Mar 22 '18 at 23:23
  • https://stackoverflow.com/questions/49374349/replace-keywords-with-user-data-angular-5 I asked this same question here, if you could look there and see if what you say applies and answer I would be very thankful – Smokey Dawson Mar 22 '18 at 23:26
  • Those answers are confusing because the "possible duplicate" is about creating _dynamic_ html and not data. See https://www.barbarianmeetscoding.com/blog/2016/04/02/getting-started-with-angular-2-step-by-step-6-consuming-real-data-with-http/ as an example – Benjamin Gruenbaum Mar 22 '18 at 23:35
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.

nbkhope
  • 7,360
  • 4
  • 40
  • 58
0

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

const innerHtml = <HTMLElement>document.querySelector('.inner-html');
innerHtml.innerHmtl.replace(...);
Vayrex
  • 1,417
  • 1
  • 11
  • 13