A Collapsable Panel component in Angular 2 and Angular 1.5

In my previous post New .component(…) method in Angular 1.5 I shared a snippet to create a simple CollapsablePanel component using the new .component() method available in Angular 1.5.
Now I’m simply showing you how to write the same component in Angular 2 and TypeScript.

Angular 2 is currently in beta 0 and the syntax may change

Live demo

Open fullpage Plunker

Angular 2 Source Code


This is the main application file and it’s used to create two instances of the panel component: the first one uses static data while the second gets its data from the class properties.

import {Component, Output, EventEmitter} from 'angular2/core';

import {Component} from 'angular2/core';
import {Panel} from './panel';

  selector: 'my-app',
  template: `
    <panel [title]="'My static title'" >static content</panel>
    <panel [title]="title" >{{body}}</panel>
  directives: [Panel]

export class App {
  title: string = 'my awesome title';
  body: string = 'my awesome content';


This component simply toggles the hide class to the body when the header is clicked and should be a good starting point to understand how to write components in Angular 2: binding, transclusion, mouse events, dynamic styling, component methods and properties.

import {Component, Output, EventEmitter} from 'angular2/core';

  selector: 'panel',
  styles: [`
    .hide {
      display: none;
  template: `
  <div class="card" *ngIf="title">
    <div class="card-header" (click)="toggle()">{{title}}  </div>
    <div  class="card-block" [ngClass]="{hide: !opened}"><ng-content></ng-content></div>
  inputs: ['title']

export class Panel {
    opened: Boolean = false;
    toggle () {
      this.opened = !this.opened;

Try in Plunker

Comparison with Angular 1.5

In the following code you can see the same component created in .component method available in Angular 1.5.
This snippet is part of the article “New .component(…) method in Angular 1.5


<panel title="ctrl.title"> {{ctrl.body}} </panel> 

<panel title="'MY PANEL'"> 
  <h4 class="card-title">My title</h4>
  <p class="card-text">additional content....</p>
  <a href="#" class="btn">Go</a>


.component('panel', {
  bindings: {
    title: '=' 
  transclude: true,
  template: [
    '<div class="card">',
     '<div class="card-header" ng-click="$ctrl.toggle()"> {{$ctrl.title}} </div>',
     '<div class="card-block" ng-class="{hide: !$ctrl.opened}" ng-transclude></div>',
  controller: function() {
    this.opened = false;
    this.toggle = function () {
      this.opened = !this.opened;

Leave a Reply

Your email address will not be published. Required fields are marked *

Published on: 27 March 2016
Posted by:
Discussion: Leave a comment