Access Parent @Component and vars from *Routed* Child Component

我的梦境 提交于 2019-12-05 01:06:52

The easiest and cleanest way is indeed to leverage a service.

The service how it could look like:

export class DomService {
    sidebarVisible: boolean = true;

    showSidebar() {
        sidebarVisible = true;
    }

    hideSidebar() {
        sidebarVisible = false;
    }

    toggleSidebar() {
        sidebarVisible = !sidebarVisible;
    }
}

In your bootstrap call add the service to the list of providers:

bootstrap(App, [
    // other providers
    DomService
]);

In the components (maybe in app.ts but also in your sidenav.ts) where you want to show/hide the sidebar add the service for injection:

constructor(private _domService: DomService) {

}

In your template, where you want to toggle/show/hide you can do now:

<sidenav-component *ngIf="_domService.sidebarVisible">...</sidenav-component>

<div id="toggle-sidebar" (click)="_domService.toggleSidebar()">toggle</div>

I like the accepted answer, seems a more robust Angular way to do it properly (especially if you are going to be adding more options).

However, I wanted quick dirty access to a global element by Id. Everybody talks about using @ViewChild but I want to walk UP the tree. I just went back to school and used this in the component method:

document.getElementById('nav-panel').className = 'hide';

If we want multiple copies of this to work (e.g. left and right side menus) we need to inject something down the children so they know which Id to look for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!