How To Access Parent Component From Child Component In Angular 9
Solution 1:
You shouldn't (definitely) be accessing private members of a 3rd party library exactly to avoid the troubles you've got into. Fortunately, if I got right what you wanna do, there is something you can do to avoid accessing these private members. I'll show 3 solutions, 2 of them implemented on the stackblitz referenced at the end of this answer.
Let's suppose you have this scenario: a parent component that has a propertyA
that you want to access directly in a child component for some reason.
Parent Component:
@Component({
template: `
<child></child>
`
})
export class ParentComponent { propertyA: string; }
Case A: Injecting the parent directly in the child
@Component({selector: 'child', ...})
exportclassChildComp {
constructor(private _parent: ParentComponent) { this._parent.propertyA = 'some value'; }
}
Case B: Getting the parent through the child's ViewContainerRef
@Component({selector: 'child', ...})
exportclassChildComp {
constructor(private viewContainerRef: ViewContainerRef) {
const _injector = this.viewContainerRef.parentInjector;
const_parent: ParentComponent = _injector.get<ParentComponent>(ParentComponent);
this._parent.propertyA = 'some value';
}
}
This is the important part: angular injectors exist exactly to do what you want, so instead of trying to get a reference to the component by yourself, the right thing to do is find out how to find an injector to do the search for you. Remember that the injectors are distributed in a hierarchy in such a way that if an injector cannot resolve a Symbol, it asks his parent injector to try to resolve it recursively until getting to the root injector. This lead us to a 3rd approach, getting the component's injector directly:
Case C: Getting the parent through the child's injector, injected directly
@Component({selector: 'child', ...})
exportclassChildComp {
constructor(private _injector: Injector) {
const_parent: ParentComponent = this._injector.get<ParentComponent>(ParentComponent);
this._parent.propertyA = 'some value';
}
}
Cases B and C work because your components are distributed in a tree of components in a parent-nth-child relation and, at some point they'll have a common injector, at the module where they are declared/imported.
I've modified your stackblitz to show both of this solution (case A used on a-component, a the case B used on b-component),
Post a Comment for "How To Access Parent Component From Child Component In Angular 9"