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

Time:08-31

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  *ngFor="let blogs of allBlogs">
{{ removeHTML(blogs.heading) }}
/div>

CodePudding user response:

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  *ngFor="let blogs of allBlogs">
{{ removeHTML(blogs.heading) }}
/div>
  • Related