0

These are the only methods I know so far:

  • @Input/@Output | This is to communicate a child with its parent and vice versa
  • @ViewChild | This is to communicate with the child component
  • @Injectable Service | share data with any component
  • rxjs/behaviorsubject | Share data with any component

I also saw an @Injectable component example, but I am not sure if that is also a way to share component data or not.

Ok, so I hope that the above text is clear enough so that everyone can understand where I am going. I need the most efficient and cleanest way(s) to share component variables and methods with any component without having to make a big mess and see performance drop.

I am thinking to share data using the following way, but I am not sure if this is efficient when having multiple components:

PARENT

import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child/child.component';

@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.scss']
})
class ParentComponent implements OnInit, AfterViewInit {
    public instance: ParentComponent;
    @ViewChild(ChildComponent) childComponent;

    constructor() {
        this.instance = this;
    }

    doSomethingWithParentMethod(strData: string) {
        console.log('parent data: ' + strData);
    }

    ngOnInit(): void {
    }

    ngAfterViewInit() {
        this.childComponent.doSomethingMethod('pass data to child in string type');
    }
}

And in the Parent HTMl file:

<app-child [parent]="instance"></app-child>

CHILD

@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.scss']
})
class ChildComponent {
    @Input() parent;

    public function doSomethingMethod(strData: string) {
        console.log('child data: ' + strData);
    }

}
Aerial
  • 1,185
  • 4
  • 20
  • 42

1 Answers1

0
@Injectable Service | share data with any component

and it changes as per requirement , but for generic service is mainly for data transfer

Ashutosh Jha
  • 15,451
  • 11
  • 52
  • 85
  • I want to use a method from other component when clicking a parent html button element. I know that this can be achieved with (click)="{{fireMethod()}}", but inside the parent method, I want to be able to fire a child method and vice versa. – Aerial Jul 02 '18 at 10:55