Reputation: 6014
I have a component hierarchy similar to this:
gggrandparent-> ggrandparent -> grandparent -> parent -> child
Child is displayed absolute
ly and needs to be aware of the the gggrandparent
s height. gggrandparent
s height changes overtime, due to some of it's children having display:none
and child
needs to respond to this changes.
What is an elegant way to get the height of the gggrandparent
inside of child.component.ts
file? Passing @Input() multipletimes seems like an overkill. The only other options I could think of is implementing Observable pattern and plain JS, but I have a feeling angular has its own way of handling this scenario.
Upvotes: 2
Views: 1206
Reputation: 657416
@Directive({
selector: '[parentHeight]'
})
export class ParentHeightDirective {
constructor(private elementRef:ElementRef) {}
int get height() {
return this.elementRef.nativeElement.height;
}
}
<grand-grand-parent parentHeight>
<grand-parent>
<parent>
<child></child>
</parent>
</grand-parent>
</grand-grand-parent>
@Component({
selector: 'child',
...
})
export class ChildComponent {
constructor(private parentHeight:ParentHeightDirective) {}
ngOnInit() { // or any other method
console.log(this.parentHeight.height);
}
}
This only works if parentHeight
isn't added to any component in between because dependency injection injects the first it finds (looking from the injecting component upwards towards AppComponent
and application root scope).
You can do this also without ParentHeightDirective
and just include the code in GrandParentComponent
and inject that instead, but a directive provides better reusability and allows to have nested GrandGrandParentComponent
s while with the directive you can specify which ones height you want by deciding where you apply the directive.
Upvotes: 2