首页 文章

Angular2从另一个组件访问变量

提问于
浏览
4

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

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

谢谢

1 回答

  • 6

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

    例如 SidebarService

    @Injectable()
    export class SidebarService {
      showSidebar: boolean = true;
    
      toggleSidebar() {
        this.showSidebar = !this.showSidebar;
      }
    }
    

    在侧边栏组件中,只需将 *ngIfSidebarService 中的 showSidebar 变量放在一起 . 另外,不要忘记在构造函数中添加服务 .

    @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

相关问题