Using (click) event in one html template to control [hidden] element in a separate template Angular 2

I have 2 TypeScript files, both with HTML templates in the @Component. Let’s say one template displays info cards that can be collapsed or expanded with [hidden]="collapsed". This function exists in either file:

    public collapsed : boolean = false;
    this.collapsed = !this.collapsed;

Then in a separate template I have a button to trigger this event

    <button clear (click)="toggleCollapsed()">
      <ion-icon name="expand"></ion-icon>
      Expand All

Basically the button and info cards are in different templates/files but displayed on the same page in the view. I need help with making the button expand/collapse the info cards even though they’re in separate templates.
I figured this topic is general enough to help others as well if answered 🙂

Leave a Reply

2 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

Just short sample:

<panel #panel>
<button (click)="panel.collapsed=!panel.collapsed">

Create component reference #panel and use it to change state.


It depends on the relationship (if any) between the two components. If there is a parent-child relationship, you can use an input property or an event (depending on which direction the communication needs to flow).

If there is no relationship, use a service with a Subject. One component will subscribe() to the Subject in order to listen for events, and the other will generate events via the Subject.

The Component Interaction Cookbook has examples of all three.