Reputation: 43
I am newbie-Angular developer and I'm learning right now.
In my project I want to make a simple page with a button and a sidenav (built with angular material) like the official material example (https://material.angular.io/components/sidenav/overview)
The problem is that I want to make the sidenav in one separate component (like sidenav.component.ts) and the "homepage" in the app.component.
The homepage is full of stuff like paragraphs, divs, and I want to implement the sidenav (obviously with the onClick event functioning in the homepage) in every page without write "md-sidenav-container" in all pages.
What I have to do?
Upvotes: 0
Views: 2072
Reputation: 8613
sidenav.component.html:
<md-sidenav-container>
<md-sidenav #sidenav mode="side">
Sidenav content
</md-sidenav>
<ng-content></ng-content>
</md-sidenav-container>
sidenav.component.ts:
@Component({
selector: 'app-sidenav',
templateUrl: './sidenav.component.html',
styleUrls: ['./sidenav.component.scss']
})
export class SidenavComponent implements OnInit {
@ViewChild('sidenav') public sidenav: MdSidenav;
constructor(private sidenavService: SidenavService) { }
ngOnInit() {
this.sidenavService.setSidenav(this.sidenav);
}
}
sidenav.service.ts:
@Injectable()
export class SidenavService {
private sidenav: MdSidenav;
public setSidenav(sidenav: MdSidenav) {
this.sidenav = sidenav;
}
public open(): Promise<MdDrawerToggleResult> {
return this.sidenav.open();
}
public close(): Promise<MdDrawerToggleResult> {
return this.sidenav.close();
}
public toggle(isOpen?: boolean): Promise<MdDrawerToggleResult> {
return this.sidenav.toggle(isOpen);
}
}
(Don't forget to add the component and the service to a module!)
In the AppComponent you can use the sidenav component like this:
<app-sidenav>
<router-outlet></router-outlet>
</app-sidenav>
The router loads the components into the router-outlet
. The router-outlet
element will be placed inside the <ng-content></ng-content>
(see sidenav.component.html).
The sidenav service enables you to control the sidenav component from every component of your application.
Inject the service inside the header component:
constructor(private sidenavService: SidenavService) { }
Create method to toggle the sidenav:
toggleSidenav() {
this.sidenavService.toggle();
}
And in the markup you can use a button like this:
<button (click)="toggleSidenav()">Toggle sidenav</button>
See small demo here:
https://stackblitz.com/edit/angular-material-kcszgq
Upvotes: 3