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);
}
}