0

I want to call a shared service function form "Another" component's view file.

For example to delete a record I want to set something like this:

<tr *ngFor="let ddata of tableData.data; let i = ddata" 
(click)="delete_record(ddata)" 
[class.active]="ddata.discountauthorizationid == selectedRow">

Here delete_record must be part of a service which I will inject in relavant component.

1

4 Answers 4

14

There is no way to call service from view (template) without injecting it into your component.

You can inject the service into a public property which lets you use the service methods inside the template as well.

constructor(public yourService: YourService) {

}

Your template:

<a (click)="yourService.yourMethod()">Test mehod</a>

Note: Please consider that the better solution is to call your component methods instead of using service methods. Services are a great way to share information among classes that don't know each other

10
  • Thanks for suggesting. I can import it in my customer. My doubt was that can I call that from view or not. I will implement this and let you know. Commented Jan 13, 2018 at 6:41
  • @Jaydeep You're welcome, I'm glad if that helps. Let me know if you need more information Commented Jan 13, 2018 at 6:42
  • I used the above solution. Now I am able to call the injected service but I can do so only in constructor function. Commented Jan 13, 2018 at 6:49
  • 2
    Please don't inspire anyone to call service in template. It's not good practice
    – Imran
    Commented Jan 13, 2018 at 6:57
  • 1
    @HDJEMAI As long as I know it's not an anti-pattern. Please take a look at this code snippet on the official doc Commented Jan 13, 2018 at 7:10
5

According to the official documentation, injecting public service to bind it in the template is not an anti-pattern.

https://angular.io/tutorial/toh-pt4

1
2

For good practice is good to use the service in private scope and use a method to return it to the view.

like in this post.

Typescript dependency injection public vs private

1
0

Every property defined within the component class can be used in the template.

2
  • private injected service, cannot be accessed from the template.
    – HDJEMAI
    Commented Jan 13, 2018 at 7:22
  • Apparently you can access a private injected service from the template in version 7.1.4. Commented Jan 28, 2019 at 19:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.