elasticrash elasticrash - 1 month ago 9
AngularJS Question

Angular 2 Child component to check parent component

what I want to achieve is different behavior of a component based on which component is its parent component. So in the following two situations the child would behave slightly different.

example A

<parent-a>
<child></child>
</parent-a>


example B

<parent-b>
<child></child>
</parent-b>


I tried to do the following

constructor(
el: ElementRef) {
this.el = el;
}

ngAfterViewInit() {
const hostElem = this.el.nativeElement;
console.log(hostElem);
console.log(hostElem.children);
console.log(hostElem.parentNode);
}


eventhough ngAfterViewInit is a bit late for me, I still got null on the parentNode

Is there any way to achieve something like that?

Answer

If you need the actual component (and not the node element) you can use the injector.

constructor(private parentB: ParentBComponent){
}

ngAfterViewInit() {
  this.parentB.someMethod()
}

Note that you have parent-a and parent-b, if you want to be able to inject any, define a base component and have both parent-a and parent-b inherit from it.

You can make it optional, you can use the Optional decorator:

constructor(@Optional() private parentB?: ParentBComponent){
} 
Comments