What is the best place to implement shared method between different components in angular?

375 views Asked by At

I'm trying to implement snackbar angular material component on my project. https://stackblitz.com/angular/ygomllvemnl?file=src%2Fapp%2Fsnack-bar-component-example.ts

This element(component) is used by 3 other components. So I need to implement the exact same method 'openSnackBar' in each component, and that will make redundancy on my code.

So what is the best place to implement the shared method 'openSnackBar', service class, helper class..., and then I can call it with one line of code?

2

There are 2 answers

1
Devang Patel On BEST ANSWER

To achieve this you need to create one shared service to share between multiple component. Make sure you add ToastService in Providers array in module.

@Injectable()
export class ToastService {

  public duration =  3000;
  public horizontalPosition: 'left' | 'start' | 'end' | 'right' | 'center' | undefined = 'left';
  public verticalPosition: 'bottom' | 'top' | undefined = 'bottom';

  constructor(private snackBar: MatSnackBar) { }

  public saveToast(
    message = 'Save Successful.',
    duration = this.duration,
    horizontalPosition = this.horizontalPosition,
    verticalPosition = this.verticalPosition
  ) {
    this.snackBar.openFromComponent(ToastComponent, {
      data: message,
      duration,
      horizontalPosition,
      verticalPosition
    });
  }
}

Then in your toast component you have to add code to display snackbar. Make sure you add ToastComponent declaration and entrycomponents array in ur module:

import { Component, Inject } from '@angular/core';
import { MAT_SNACK_BAR_DATA, MatSnackBar } from '@angular/material';

@Component({
    selector: 'general-toast',
    template: `
    <div>
        <div>
            <span [innerHTML]="data> </span>
        </div>
        <div>
            <button mat-icon-button (click)="dismissToast()">
                <mat-icon>close</mat-icon>
            </button>
        </div>
    </div>
    `,
})

export class ToastComponent {

    constructor(
        @Inject(MAT_SNACK_BAR_DATA) public data: any,
        public snackBar: MatSnackBar
    ) { }

    public dismissToast(): void {
        this.snackBar.dismiss();
    }

}

You are all set now. You just need to Inject ToastService in the constructor and call from your component.

0
rassakra On

while it will be used in multiple Components then it should be in Service so it can be injected in multiple components (initialized only once, singleton).