Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using alert message from other component in angular

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.

like image 790
BlueCat Avatar asked Jul 20 '26 17:07

BlueCat


2 Answers

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);
}
like image 121
Aer0 Avatar answered Jul 23 '26 07:07

Aer0


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

like image 33
matirmv Avatar answered Jul 23 '26 08:07

matirmv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!