Navbar control and formatting is often needed throughout an app, so a NavbarService is useful. Inject in those components where you need.
navbar.service.ts:
import { Injectable } from '@angular/core';
@Injectable()
export class NavbarService {
visible: boolean;
constructor() { this.visible = false; }
hide() { this.visible = false; }
show() { this.visible = true; }
toggle() { this.visible = !this.visible; }
doSomethingElseUseful() { }
...
}
navbar.component.ts:
import { Component } from '@angular/core';
import { NavbarService } from './navbar.service';
@Component({
moduleId: module.id,
selector: 'sd-navbar',
templateUrl: 'navbar.component.html'
})
export class NavbarComponent {
constructor( public nav: NavbarService ) {}
}
navbar.component.html:
<nav *ngIf="nav.visible">
...
</nav>
example.component.ts:
import { Component, OnInit } from '@angular/core';
import { NavbarService } from './navbar.service';
@Component({
})
export class ExampleComponent implements OnInit {
constructor( public nav: NavbarService ) {}
}
ngOnInit() {
this.nav.show();
this.nav.doSomethingElseUseful();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…