Tutorial Call Parent Function From Child In Angular 4

There are several ways to call the function() in parent component from the child component of angular 4 such as input bindings, setters, service, etc. According to my understanding, the easiest way is using the service. In this tutorial, I will share how to communicate parent and child component using router-outlets and services method.

Another article: Simple Login Form Angular 4 Tutorial For Beginner

As written in the official documentation angular 4, there are seven ways to communicate with parent and child, among others:

  1. Pass data from parent to child with input binding.
  2. Intercept input property changes with a setter.
  3. Intercept input property changes with ngOnChanges().
  4. Parent listens for child event.
  5. Parent interacts with child via local variable.
  6. Parent calls an @ViewChild().
  7. Parent and children communicate via a service.

To be able to communicate via service, we need an angular 4 service that can be executed on each component. We start the following tutorial

Call Parent Function From Child Angular 4 Tutorial

Tutorial angular 4 call parent function from child via service and router-outlet

Note: I use angular-cli to create an example of this project

1. Create an angular 4 service with the following command

2. Add the following script to com-parent-child.service.ts

3. Import service and add provider in app.module.ts

Examples of using the service are as follows.

1. add the following script to the parent component

2. Add the following script to the child component

3. Add the following script to the child template

If the above script executed, the application will work like the following picture.

Call Parent Function From Child Angular 4 Tutorial

Related article: Tutorial Create Angular 4 Currency Format Directive For Textbox

Reference:

Hopefully, tutorial angular 4, How to call parent function from child component can be useful for your application.

The following two tabs change content below.
This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Leave a Comment

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.