Search code examples
angularangular2-components

Update class of a component from a different component in Angular2


I'm trying to update a class of a element available in'sidebar' component when a button is clicked which is available in a different component named 'header'

My current setup:

app.ts

@Component({
  selector: 'my-app',
  template: `
    <div>
      <app-header></app-header>
      <app-sidebar></app-sidebar>
    </div>
  `,
})

header.ts

@Component({
  selector: 'app-header',
  template: '<header><button (click)="isActiveSidebar = false">close aside</button></header>'
})

export class HeaderComponent implements OnInit {
  isActiveSidebar = true;
}

sidebar.ts

@Component({
  selector: 'app-sidebar',
  template: '<aside [class.aside-hidden]="!isActiveSidebar">sidbar</aside>'
})

Plunkr https://plnkr.co/edit/7iTE8Nb4R0TbUqhYv3QG?p=preview

What I was expecting here, when I clicked the button in header component, the property isActiveSidebar would set to false and the aside element in sidebar component would a get the class 'aside-hidden'

Same kind of setup worked for me when I'm using the same inside one single component. Currently I have no idea on how to get this done between 2 different component. I would really appreciate if you could help me on this by updating the given plunkr demo.


Solution

  • Create an @Output() in the HeaderComponent and wire it up with the sidebar:

    @Component({
      selector: 'app-header',
      template: '<header><button (click)="deactivate()">close aside</button></header>'
    })
    
    export class HeaderComponent implements OnInit {
      @Output() deactivateSidebar:EventEmitter<bool> = new EventEmitter<bool>();
      isActiveSidebar = true;
    
      deactivate() {
        this.isActiveSidebar = false;
        this.deactivateSidebar.emit(null);
      }
    }
    
    @Component({
      selector: 'my-app',
      template: `
        <div>
          <app-header (deactivateSidebar)="sidebar.deactivate()"></app-header>
          <app-sidebar #sidebar></app-sidebar>
        </div>
      `,
    })
    
    class AppSidebarComponent {
      deactivate() {
        this.isActiveSidebar = false;
      }
    }