Search code examples
angularangular2-services

How to Call shared service function in angular 2 View?


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.


Solution

  • 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