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

后端 未结 2 554
半阙折子戏
半阙折子戏 2021-01-18 10:17

I\'m currently teaching myself Angular2 and I have a practical problem that would be easy to rectify in AngularJS but currently I\'m looking through examples to find a solut

相关标签:
2条回答
  • 2021-01-18 10:54

    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:

    • Delegation: EventEmitter or Observable in Angular2
    0 讨论(0)
  • 2021-01-18 11:05

    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);
          }
    }
    
    0 讨论(0)
提交回复
热议问题