1

I am creating a custom function in a service file where I am trying to limit the string length. But I don't know how to call that function from angular view component.

generalservice.ts
-----------------------

export class GeneralService {

  constructor() { }

  removeHTML(str:any){ 
      var tmp = document.createElement("DIV");
      tmp.innerHTML = str;
      return tmp.textContent || tmp.innerText || "";
  }
}

app.component.ts
--------------------
doSomething(){
    
    subscribe(data => {
        this.allBlogs = data.blogs.data;
        
        }
    );
  }

app.component.html
----------------------
<div class="post-item border" *ngFor="let blogs of allBlogs">
{{ removeHTML(blogs.heading) }}
/div>
Abhishek
  • 149
  • 1
  • 1
  • 15

1 Answers1

1

You can just create a public variable with the same name removeHTML and then assign the method of the service to this variable, then it will call the service method!

generalservice.ts
-----------------------

export class GeneralService {

  constructor() { }

  removeHTML(str:any){ 
      var tmp = document.createElement("DIV");
      tmp.innerHTML = str;
      return tmp.textContent || tmp.innerText || "";
  }
}

app.component.ts
--------------------
doSomething(){
    
    subscribe(data => {
        this.allBlogs = data.blogs.data;
        
        }
    );
  }

removeHTML = this.generalService.removeHTML; // <- change made here

app.component.html
----------------------
<div class="post-item border" *ngFor="let blogs of allBlogs">
{{ removeHTML(blogs.heading) }}
/div>
Naren Murali
  • 19,250
  • 3
  • 27
  • 54
  • Yes sir I have given – Abhishek Aug 30 '22 at 06:38
  • Although this answers your question and will work, I don't think this is a good solution to what I think your actual problem is. What you probably want to do instead is use a `custom pipe` and move your logic into the pipe to ' limit the string length', a quick search for examples gave me [this](https://stackoverflow.com/questions/44669340/how-to-truncate-text-in-angular2). You might want to make your pipe a `pure` one as well so it only runs once and not on every change detection, for performance reasons. – Jayme Aug 30 '22 at 07:15