Here are some methods I have been using:
- @Input/@Output | Communication between parent and child components
- @ViewChild | Communication with child components
- @Injectable Service | Sharing data across components
- rxjs/behaviorsubject | Data sharing among components
I came across an @Injectable component example, but I am unsure if it is another way to share component data.
I aim for the most efficient and clean approach(es) to share variables and methods between components without compromising performance or creating confusion.
I am considering data sharing in the following manner, though I am uncertain about its efficiency when dealing with 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');
}
}
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);
}
}