繁体   English   中英

Angular2从另一个组件访问变量

[英]Angular2 access variables from another component

尝试EventEmitter但没有机会和如此少的文档...任何帮助赞赏

我有一个名为sidebar的组件和另一个名为header的组件,当你点击标题中的一个按钮时,它应该隐藏侧边栏...你如何在angular2中实现这一点?

谢谢

使用您在组件之间共享的服务非常简单。

例如SidebarService

@Injectable()
export class SidebarService {
  showSidebar: boolean = true;

  toggleSidebar() {
    this.showSidebar = !this.showSidebar;
  }
}

在侧边栏组件中,只需在showSidebar *ngIf带有showSidebar变量的*ngIf SidebarService 另外,不要忘记在构造函数中添加服务。

@Component({
  selector: 'sidebar',
  template: `
      <div *ngIf="_sidebarService.showSidebar">This is the sidebar</div>
  `,
  directives: []
})
export class SidebarComponent {
  constructor(private _sidebarService: SidebarService) {

  }
}

在组件中,您要处理侧栏的切换,还会注入SidebarService并使用服务方法添加click事件。

@Component({
  selector: 'my-app',
  template: `
    <div>
      <button (click)="_sidebarService.toggleSidebar()">Toggle Sidebar</button>
      <sidebar></sidebar>
    </div>
  `,
  directives: [SidebarComponent]
})
export class App {
  constructor(private _sidebarService: SidebarService) {

  }
}

不要忘记将SidebarService添加到引导程序中的提供程序:

bootstrap(App, [SidebarService])

例如使用Plunker

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM