Using alert message from other component in angular

64,775

Solution 1

You definitely have to use a service for such a functionality. You have to create a "service" folder in which you will create like a alert.service.ts file. in this file you will define the alert function you want to display in all your components.

Then you will import this service in the components which need it.

I suggest you to read this tuto from the angular documentation, which is really handy : https://angular.io/tutorial/toh-pt4

Solution 2

You should rather put the string into your component instead of the whole alert itself. Afterwards you can call the alert in your click handler.

Only pass the string to your child component.

export class CenterPage {
  public message = "Warning";

Handle the click within a dedicated function.

<button (click)="myFunc"></button>

Do your logic stuff in your function.

public myFunc() {
  alert(this.message);
}
Share:
64,775
BlueCat
Author by

BlueCat

Updated on April 05, 2020

Comments

  • BlueCat
    BlueCat about 4 years

    I googled several examples about using functions/variables from other components in Angular 4/5. They helped me a bit for understanding but I still couldn't figure out the solution to my problem.

    I wanna call a standard JavaScript alert from another component.

    I have a component, which has a variable like this:

    center.ts

    export class CenterPage {
      public message = new alert("Warning");
    

    center.html

    <products [message]="message"></products>
    

    I'm using @Input to get the message in products.ts

    export class ProductsComponent {
      @Input() message;
    

    Now I want to show the alert, when the user clicks on a button in product.html

    <button (click)="message"></button>
    

    This seems to be wrong and I think this is not the right way how I'm trying to show the alert when the user clicks on the button.

    How can I do this correctly?

    EDIT

    This is only one example. In the end I will have to call the same alert in several components. So I try to have only one function which I can call from all components so I won't have redundant code.

  • BlueCat
    BlueCat about 6 years
    Thanks, that's a good idea but the problem is, that I need to call this alert from several components and then I would have to add "myFunc()" in every single component. I'm trying to avoid redundant code
  • Aer0
    Aer0 about 6 years
    Use a Service instead. You'd just need to inject the service into all components.
  • BlueCat
    BlueCat about 6 years
    Ya I found this solution too when I googled but it seems kinda "exaggerated" to me for just using an alert.. Isn't there a easier way?
  • Aer0
    Aer0 about 6 years
    You could also stick to your solution as long as you pass in a whole function (like myFunc()) to @Input() message. Yet this isn't the best approach. Best practice would be to use a Service instead.