我在标题中添加了一个按钮来显示/隐藏导航抽屉。由于按钮和导航抽屉位于不同的组件中,那么哪个选项更容易沟通?
发布于 2018-05-30 16:29:07
您可以使用服务来预置导航栏的状态。为此,您可以在服务中使用可观察布尔型。单击该按钮时,将其设置为true或false。然后,从导航栏组件订阅该服务属性的,以隐藏导航栏中的内容。
在您的服务中
@Injectable()
export class GlobalDataService {
private showNavigationBar = new Subject<boolean>();
constructor() {
}
public getNavigationbarState(): Observable<boolean> {
return this.showNavigationBar.asObservable();
}
public setNavigationbarState(value: boolean) {
return this.showNavigationBar.next(notification);
}
}
在header组件按钮中,单击event。
constructor(private globalDatServce:GlobalDataService) {
}
public onButtonClick(): void {
this.globalDataService.setNavigationbarState(true); // pass true or false as needed
}
在导航栏组件构造函数中。
constructor(private globalDatServce:GlobalDataService) {
this.globalDatServce.getNavigationbarState().subscribe((res) => {
this.shownavigation = res;
});
}
在模板中
<div *ngIf="shownavigation">
// navigation content goes here
</div>
发布于 2018-05-30 17:46:53
服务的“简化”版本是
//in header
<div *ngIf="shownavigation">....</div>
constructor(private globalDataService:GlobalDataService){}
get shownavigationn()
{
return this.globalDataService.shownavigation
}
和
//In component
<button (click)="click()">Click me!</button>
constructor(private globalDataService:GlobalDataService){}
set shownavigationn(value)
{
this.globalDataService.shownavigation=value
}
click()
{
this.showNavigation=!this.showNavigation
}
https://stackoverflow.com/questions/50599685
复制相似问题