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.
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With