Toggle property in parent Component from Child Component in Angular2 (similar to $emit in AngularJS)

只愿长相守 提交于 2019-12-01 18:09:48
Thierry Templier

I could leverage a shared service that define an EventEmitter property. Your App component will subscribe on it to be notified when the corresponding event is trigger by the TopNavigation component.

  • Shared service

    @Injectable()
    export class MenuService {
      showMenuEvent: EventEmitter = new EventEmitter();
    }
    

    Don't forget to define the corresponding provider in the boostrap function to be able to share the same instance of the service for the whole application: `bootstrap(App, [ MenuService ]);

  • App component

    @Component({ ... })
    export class App {
      showMenu: boolean = false;
      constructor(menuService: MenuService) {
        menuService.showMenuEvent.subscribe(
          (showMenu) => {
            this.showMenu = !this.showMenu;
          }
       );
     }
    

    }

  • TopNavigation component:

    export class TopNavigation {
      constructor(private menuService: MenuService) {
        // Things happening here
      }
    
      toggleMenu():void {
        this.showMenu = this.showMenu;
        this.menuService.showMenuEvent.emit(this.showMenu);
      }
    }
    

See this question for more details:

You can use two-way binding.

<top-navigation [(toggleMenu)]="showMenu"></top-navigation>

maybe one-way would do as well, I don't know your exact requirements

<top-navigation (toggleMenuChange)="showMenu=$event"></top-navigation>
export class TopNavigation {
      @Output() toggleMenuChange: EventEmitter = new EventEmitter();

      // for two-way binding
      @Input() toggleMenu:boolean = false;

      constructor() {
        // Things happening here
      }

      toggleMenu():void {
        this.toggleMenu = !this.toggleMenu;
        this.toggleMenu.emit(this.toggleMenu);
      }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!