Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a function from Angular service class in angular view component?

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading