CodeBeatz
CodeBeatz

Reputation: 1981

How can I comunicate from child to grandfather component?

I'm developing one application with Angular 2. In my scenario there are three components:

Below SearchComponent code:

<form>
    ... there my form input
</form>

<!-- result is a property inside my SearchComponent class -->
<search-result [(value)]="result"></search-result>

Below SearchResultComponent code:

<div>
    <table>
        ... there is my table
        ... foreach row I have one edit component
        <tr>
            <td>data</td>
            <td>
                <edit></edit>
            </td>
        </tr>
    </table>
</div>

Below my EditComponent code:

<form>
    ... There are edit inputs...
</form>

<button label="Salva" (click)="edit()"></button>

<edit [(documentId)]="id"></edit>

My goal is that when I click on save button I would reload my result.

How can I reach the goal?

Thanks

Upvotes: 1

Views: 1809

Answers (1)

Andresson
Andresson

Reputation: 1307

There are at least 2 ways to do this.
1. Option: Create a singleton service like @AsifKarimBherani suggested.

..The singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

In simple use cases in Angular 2+ you can achieve such result by providing the service only in the app.module.ts (If using the standard file/folder structure from Angular-CLI).

2. Option: Create a bridge from grandchild to parent and another bridge from parent to grandparent using @Output decorator.

The child component exposes an EventEmitter property with which it emits events when something happens. The parent binds to that event property and reacts to those events.

The child's EventEmitter property is an output property, typically adorned with an @Output decoration

Hope this gave you some ideas.

Upvotes: 1

Related Questions