Thursday, March 9, 2017

Angular 2 toggle button | Angular 2 collapsible panel

Let us check how we can build a toggle button using angular js 2. Same code you can use for building collapsible panel as well. It is almost similar like angular js 1 concept except some syntax changes. So if you are an angular js 1 guy, you are the best person to learn angular js2 as well :) :).

Here I have used ngif(ng-if in angular js 2) and angular 2 click method(ng-click in angular js 2) to achieve this.

Component code


@Component({
    selector: 'my-app',
    template: `<h2>{{title}}</h2>
        <button (click)="showSelected()">
            <span *ngIf="!selected">Show</span>
            <span *ngIf="selected">Hide</span>
        </button>
        <div>
            <ul *ngIf="selected">
                <li *ngFor="let i of items">
                    <p>{{i.name}} ({{i.exp}})</p>
                </li>
            </ul>
        </div>
        `
})

export class App {
    title: string;
    items: any[];
    selected: boolean;
    constructor() {
        this.title = "Angular 2 Toggle";
        this.selected = true;
        this.items = [{
            name: 'Prashobh',
            exp: '9',
        },
        {
            name: 'Abraham',
            exp: '15',
        },
        {
            name: 'George',
            exp: '2',
        },
        {
            name: 'John',
            exp: '20',
        }
        ]
    }
    showSelected(item) {
        this.selected = !this.selected;
    }
}

Related Post

1. ng-repeat in angular js 2

2. Angular 2 filter using pipe concept

3. ng-click in angular js 2

2 comments :

  1. this one is cool, thanks

    ReplyDelete
  2. Great, Angular is one of the best java script frame work, Now Angular 4 is On demand, So developer must learn AngularJs 4 to become expert in AngularJS 4

    ReplyDelete