typescript - Angular 4 Accessing elements from another component -
i trying create side-nav , toolbar. want create separate components each have created 2 different components
code <app-sidenavmenu>
<md-sidenav-container class="sidenav-container"> <md-sidenav mode="push" class="sidenav" opened="false" #sidenav> <md-list> <md-list-item>...</md-list-item> </md-list> </md-sidenav> </md-sidenav-container>
and code <app-toolbar>
<md-toolbar> <span><button md-button (click)="sidenav.toggle()"><md-icon>menu</md-icon></button></span> <span><h2>app name</h2></span> </md-toolbar>
and in third home component using above components
now wanted access #sidenav
side-nav component toolbar component side-nav toggle toggle function
how achieve this.
one way have appcomponent manage state of sidebar. has object both sidebar , navbar have reference too. navbar changes , sidebar response.
@component({ selector: 'my-app', template: ` <my-navbar [state]="state"></my-navbar> <my-sidebar [state]="state"></my-sidebar> ` }) export class app implements oninit { state = { showsidebar: true; }; } @component({ selector: 'my-navbar', template: ` <div> <span class="toggle" (click)="togglesidebar()">toggle</span> navbar </div> ` }) export class navbar implements oninit { @input() state: any; togglesidebar() { this.state.showsidebar = !this.state.showsidebar; } } @component({ selector: 'my-sidebar', template: ` <div *ngif="state.showsidebar">sidebar</div> ` }) export class sidebar implements oninit { @input() state: any; }
here's plunker:
https://plnkr.co/edit/ldpg25?p=preview
an alternative have service keeps track of navbar state you. pretty simple service require use of subject. subjects kind of events, navbar call service emit toggle, , sidebar subscribe service , toggle pushed it.
hopefully makes sense, feel free ask questions!
Comments
Post a Comment