最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I access the DOM element of another component in Angular? - Stack Overflow

programmeradmin4浏览0评论

My app is structured like this:

<nav></nav>
<router-outlet></router-outlet>
<footer></footer>

In the router-outlet I have different ponents based on the route. In a few of those pages I need to access the DOM elements of either the nav or the footer for things like pageYOffset, height and etc. for sticky positioning. I know of things like ViewChild, Renderer2 and ElementRef but not really sure how it would work. Do I create a service? What might that look like?

My app is structured like this:

<nav></nav>
<router-outlet></router-outlet>
<footer></footer>

In the router-outlet I have different ponents based on the route. In a few of those pages I need to access the DOM elements of either the nav or the footer for things like pageYOffset, height and etc. for sticky positioning. I know of things like ViewChild, Renderer2 and ElementRef but not really sure how it would work. Do I create a service? What might that look like?

Share Improve this question asked Oct 23, 2018 at 15:10 user1842315user1842315 3171 gold badge3 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

Assuming that the child ponents are of type NavComponent and FooterComponent, you can retrieve the corresponding DOM elements with @ViewChild(..., { read: ElementRef }) in ngAfterViewInit:

@ViewChild(NavComponent, { read: ElementRef }) private navElementRef: ElementRef;
@ViewChild(FooterComponent, { read: ElementRef }) private footerElementRef: ElementRef;

ngAfterViewInit() {
  const navElement = this.navElementRef.nativeElement;
  const footerElement = this.footerElementRef.nativeElement;
  ...
}

See this stackblitz for a demo.


These elements can be made accessible to other parts of the application with a simple service:

export class AppElementsService {
  public navElement: HTMLElement;
  public footerElement: HTMLElement;
}

and set in the application ponent:

@ViewChild(NavComponent, { read: ElementRef }) private navElementRef: ElementRef;
@ViewChild(FooterComponent, { read: ElementRef }) private footerElementRef: ElementRef;

constructor(private appElementsService: AppElementService) { }

ngAfterViewInit() {
  this.appElementsService.navElement = this.navElementRef.nativeElement;
  this.appElementsService.footerElement = this.footerElementRef.nativeElement;
}

Note: you may need to set the display style attribute of the nav and footer ponents to block or inline-block in order to get the position and size of the corresponding elements.

发布评论

评论列表(0)

  1. 暂无评论